我不想解析 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 中的各种文件测试,但它们都返回相同的代码。
答案1
请测试该文件。
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
手册页以了解其他可能性。
答案2
$ test -f /etc/passwd
$ echo $?
0
$ test -f /etc/passwds
$ echo $?
1
答案3
其他答案并没有真正区分不同的情况,但这个perl
脚本确实区分了:
$ cat testscript
chk() {
perl -MErrno=ENOENT,EACCES -e '
exit 0 if -e shift; # exists
exit 2 if $! == ENOENT; # no such file/dir
exit 3 if $! == EACCES; # permission denied
exit 1; # other error
' -- "$1"
printf "%s %s " "$?" "$1"
[[ -e "$1" ]] && echo "(exists)" || echo "(DOES NOT EXIST)"
}
chk /root
chk /etc/passwd/blah
chk /x/y/z
chk /xyz
chk /root/.profile
chk /root/x/y/z
$ ./testscript
0 /root (exists)
1 /etc/passwd/blah (DOES NOT EXIST)
2 /x/y/z (DOES NOT EXIST)
2 /xyz (DOES NOT EXIST)
3 /root/.profile (DOES NOT EXIST)
3 /root/x/y/z (DOES NOT EXIST)
请参阅stat(2)
手册页以了解可能的错误代码。