【发布时间】:2011-11-15 00:54:02
【问题描述】:
我在网上某处看到写的代码,我想知道“$?”到底是什么?做/给我们。 谷歌搜索没有帮助。
这是我在其中看到的代码:
#!/bin/sh
ping -c 2 localhost
if [ $? != 0 ] ; then
echo "Couldn't ping localhost, weird"
fi
ping -c 2 veryweirdhostname.noend
if [ $? != 0 ] ; then
echo "Surprise, Couldn't ping a very weird hostname.."
fi
echo "The pid of this process is $$"
取自:http://efod.se/writings/linuxbook/html/shell-scripts.html
【问题讨论】:
-
stackoverflow.com/questions/90418/… 给出最后执行命令的退出状态
-
$?是最后一条命令的返回码
-
和往常一样,
cmd; if [ $? != 0 ]; then stuff; fi的使用是一种反模式,它更优雅地写成if ! cmd ; then stuff; fi(前提是您不需要stuff中的$?的值,其中案例if cmd; then : nothing; else stuff with $?; fi) 甚至cmd || stuff