澄清 shell 脚本中 test -f 与 test -e 的差异和用法

Lin*_*eak 4 shell-script files test

代码审查中

有人指出我应该改变这样的test结构:

[ ! -f "$1" ] &&
print_error_and_exit "The given argument is not an existing file."
Run Code Online (Sandbox Code Playgroud)

类似的东西,特别是:

[ ! -e "$1" ] ...
Run Code Online (Sandbox Code Playgroud)

test -e除了在info test; 中,我找不到任何关于此的信息 引用相关章节:

16.3.3 File characteristic tests
--------------------------------

‘-e FILE’
     True if FILE exists.

16.3.1 File type tests
----------------------

‘-f FILE’
     True if FILE exists and is a regular file.
Run Code Online (Sandbox Code Playgroud)

由于我想 100% 了解我在做什么,我可以要求更深入地说明这两种test命令的差异和用法吗?

Ign*_*ams 9

一些“文件”实际上是目录 ( -d)、FIFO ( -p)、设备节点 (-b-c) 等。它们存在,但不是常规文件。


Tob*_*ght 4

这听起来像是我的评论!

-e对于非常规文件,使用 进行测试将返回 true:目录、管道、套接字、设备等。

请注意,符号链接是一种特殊情况 -通常使用指向test文件的类型,而不是链接本身(除了,又名)。test -Ltest -h

在参考评论中,您可能希望能够从 FIFO 中读取数据。(另一方面,从目录中读取肯定行不通)。

在稍后的审查中,您确实不想覆盖设备(尽管您可能想写入 FIFO,因此请根据您的需要进行微调)。