Unix

如何區分“沒有這樣的文件或目錄”和“權限被拒絕”

  • December 16, 2021

我寧願不解析 STDERR,但我想不出另一種方法來以程式方式區分兩者之間的區別:

$ ls /net/foo.example.com/bar/test
/net/foo.example.com/bar/test: Permission denied
$ ls /sdfsdf
/sdfsdf: No such file or directory

無論我嘗試什麼命令,它們似乎都返回相同的錯誤程式碼,所以這是一個死胡同:

$ ls /net/foo.example.com/bar/test
/net/foo.example.com/bar/test: Permission denied
$ echo $?
2
$ ls /sdfsdf
/sdfsdf: No such file or directory
$ echo $?
2

我在 perl 中嘗試了各種文件測試,但它們都返回相同的程式碼。

而是測試文件。

test -e /etc/shadow && echo The file is there

test -f /etc/shadow && echo The file is a file

test -d /etc/shadow && echo Oops, that file is a directory

test -r /etc/shadow && echo I can read the file

test -w /etc/shadow && echo I can write the file

有關其他可能性,請參見test手冊頁。

$ test -f /etc/passwd
$ echo $?
0

$ test -f /etc/passwds
$ echo $?
1

引用自:https://serverfault.com/questions/597325