为什么“file xxx.src”导致“无法打开`xxx.src'(没有这样的文件或目录)”但退出状态为0(成功)?

pmo*_*mor 17 linux file-command exit-status

为什么file xxx.src导致cannot open `xxx.src' (No such file or directory)但退出状态为 0(成功)?

$ file xxx.src ; echo $?
xxx.src: cannot open `xxx.src' (No such file or directory)
0
Run Code Online (Sandbox Code Playgroud)

注意:比较ls

$ ls xxx.src ; echo $?
ls: cannot access 'xxx.src': No such file or directory
2
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 26

此行为记录在 Linux 上,并且是 POSIX 标准所要求的。来自fileUbuntu 系统的手册:

EXIT STATUS
     file will exit with 0 if the operation was successful or >0 if an error was encoun?
     tered.  The following errors cause diagnostic messages, but don't affect the pro?
     gram exit code (as POSIX requires), unless -E is specified:
           •   A file cannot be found
           •   There is no permission to read a file
           •   The file type cannot be determined
Run Code Online (Sandbox Code Playgroud)

-E(如上所述):

EXIT STATUS
     file will exit with 0 if the operation was successful or >0 if an error was encoun?
     tered.  The following errors cause diagnostic messages, but don't affect the pro?
     gram exit code (as POSIX requires), unless -E is specified:
           •   A file cannot be found
           •   There is no permission to read a file
           •   The file type cannot be determined
Run Code Online (Sandbox Code Playgroud)

-ELinux 上的非标准选项记录为

对于文件系统错误(找不到文件等),不是像 POSIX 要求的那样将错误作为常规输出处理并继续,而是发出错误消息并退出。

file实用程序的 POSIX 规范说(我的重点):

如果file操作数命名的文件不存在、无法读取或无法确定文件操作数命名的文件类型,则不应视为影响退出状态的错误

  • 有人在使用德沃夏克。我知道我认出了那个文件名。 (2认同)

Gil*_*il' 26

肤浅的答案是它一直都是这样,所以每个人都这样做。POSIX指出

如果文件操作数命名的文件不存在、无法读取或文件操作数命名的文件类型无法确定,则不应视为影响退出状态的错误。

不幸的是,没有给出任何理由,所以 POSIX 声明这是历史实践的唯一明显原因。

file实用程序于 1973 年首次出现在Unix Research 版本 4中。当时,标准实用程序不检查错误(即使进程至少从版本 3开始就有返回状态,如果不是版本 2)。例如,cat如果文件在版本 8 中不存在,则开始返回非零状态:版本 7只是打印了一条错误消息并继续运行。但即使到版本 10,也file只有在无法读取magic文件时才会以非零状态退出,如果无法读取数据文件则不会。

file不失败的一个可能原因是它不仅对文件内容感兴趣,还对文件类型感兴趣,它认为“不存在”是一种特殊的文件,与目录、符号链接、损坏的符号链接一起,等等。这是一个弱的理由,因为不可读的文件实际上并不是一种特殊的文件,它是一个无法确定其性质的文件,任何明智的衡量标准都是错误的。此外,它可以适用于ls,如果从版本 10 起给出不存在的文件名,它仍然不会返回错误,但这最终成为普遍做法。

所以看来, 的返回状态file是一个时间忘记的错误。现在可能有一些脚本依赖于file在文件不存在时不返回错误状态,现在更改为时已晚。