Linux 文件命令新手教程(5 例)
在此页
- Linux 文件命令
- Q1。如何使用文件命令?
- Q2。如何测试多个文件?
- Q3。如何使文件仅显示输出类型?
- Q4。如何查看MIME类型的文件?
- Q5。如何更改输出中的分隔符?
- 结论
在 Linux 命令行上工作时,有时您可能会遇到一个存档文件(比如 .zip 文件),但它的扩展名(或没有扩展名)会给出不同的提示。在这样的时候,文件命令被证明是有用的,因为它可以让您确定实际的文件类型。
在本教程中,我们将使用一些易于理解的示例来讨论 file 命令的基础知识。但在我们这样做之前,值得一提的是,这里提到的所有示例都已经在 Ubuntu 18.04 LTS 机器上进行了测试。
Linux文件命令
正如开头提到的,Linux 中的文件命令可以让您查看正在处理的文件类型。以下是它的语法:
file [OPTIONS] file1 file2 ....
以下是工具手册页对其的解释:
file tests each argument in an attempt to classify it. There are three
sets of tests, performed in this order: filesystem tests, magic tests,
and language tests. The first test that succeeds causes the file type to
be printed.
The type printed will usually contain one of the words text (the file
contains only printing characters and a few common control characters and
is probably safe to read on an ASCII terminal), executable (the file con?
tains the result of compiling a program in a form understandable to some
UNIX kernel or another), or data meaning anything else (data is usually
“binary” or non-printable). Exceptions are well-known file formats (core
files, tar archives) that are known to contain binary data. When adding
local definitions to /etc/magic, make sure to preserve these keywords.
Users depend on knowing that all the readable files in a directory have
the word “text” printed. Don't do as Berkeley did and change “shell
commands text” to “shell script”.
以下是一些问答式的示例,可以让您更好地了解文件命令的工作原理。
Q1。如何使用文件命令?
很简单,只需将文件名作为输入执行文件即可。例如:
file test
由于 test 是我系统上的一个目录,文件命令就告诉了我这一点。这是它产生的输出:
test: directory
Q2。如何测试多个文件?
这也很简单。只需将文件名作为输入传递,类似于我们在上一个示例中所做的方式。
这是一个例子:
file test test.txt .local
这是此命令产生的输出:
test: directory
test.txt: ASCII text
.local: directory
Q3.如何使文件仅显示输出类型?
到目前为止,您在文件命令输出中可以看到,输出包含两件事:文件名及其类型。但是,如果需要,您可以使 file 只生成输出类型。这可以使用 -b 命令行选项来完成。
例如,以下命令:
file -b test
在我的系统上产生了以下输出:
directory
Q4.如何查看MIME类型的文件?
要查看文件的 MIME 类型,请使用 -i 命令行选项。这是一个例子:

Q5.如何更改输出中的分隔符?
正如我们上面所讨论的,在默认模式下,文件命令在输出中产生一个文件名,后面跟着它的类型。这两个详细信息均由冒号 (:) 分隔。但是,如果需要,您可以使用 -F 命令行选项更改此分隔符。
例如:
file -F " +" test
产生了以下输出:
test + directory
结论
总而言之,锉刀是猫咪必备的重要工具。我们只是触及了表面,因为该工具在命令行选项方面提供了更多功能。完成我们在这里讨论的任何内容后,您可以前往文件命令手册页了解更多信息。