判断退出状态码
变量 ? 保存着上一个执行的命令(通常是完成了的前台进程)的退出状态码。
下面的例子展示了一个简单的 test:
anny ~> if [ $? -eq 0 ]
More input> then echo 'That was a good job!'
More input> fi
That was a good job!
anny ~>
下面的例子展示了 TEST-COMMANDS 能够是任意的能返回退出状态码的 unix 命令,那个 if 再次返回了值为 0的状态码:
anny ~> if ! grep $USER /etc/passwd
More input> then echo "your user account is not managed locally"; fi
your user account is not managed locally
anny > echo $?
0
anny >
能通过接下来得到同样的结果:
anny > grep $USER /etc/passwd
anny > if [ $? -ne 0 ] ; then echo "not a local account" ; fi
not a local account
anny >
如何判断某个命令是否存在
可以用 shell 中的 command -v 来检查命令的退出状态。如判断若命令 git 不存在
if ! command -v git > /dev/null; then
# dosth.
fi
这里若命令 git 存在,则 command -v git 会在 std 中输出 git 命令的路径,所以将输出值重定向到 /dev/null 以避免不必要的 std 输出,直接用 if 可判断退出状态。
参考

