我对在脚本中使用 test 命令感到困惑。通常我对 Linux 有经验,但最近我无法解决以下问题:
我想使用
test -d dir
检查目录是否存在。根据目录是否存在,我想返回 echo
输出。所以 if
语句看起来有点像这样:
if test -d $HOME/dir
then
echo $?
echo The directory exists.
else
echo $?
echo The directory does not exist.
fi
我现在的问题是理解错误代码。为什么当
if
命令的错误代码为0时,True
语句会进入条件test
块?
根据我的理解,应该是相反的,特别是如果我不指定条件而只是使用 if test …
。
我已经阅读了
test
的 man 文件,但我并没有变得更聪明。此外,我测试了使用 if
语句的条件,如下所示:
test -d $HOME/dir
exitcode=$(echo $?)
if [ "$exitcode" -ne 0 ]
then
echo -e exit is $exitcode
echo -e does not exist
else
echo -e exit is $exitcode
echo -e exists
fi
exit
当然,两个脚本返回相同的输出,但同样:我不知道为什么在退出代码时将
test
命令与 if
语句一起使用会使 if
语句进入条件 true
块内部是 0。
因为退出代码
0
表示成功,而其他所有退出代码都表示错误。
尝试一下:
true && echo "$?";
false && echo "$?";
有用的资源: