
命令的返回值是其退出状态,退出状态用于检查命令执行的结果(成功/失败)。如果退出状态为0,则命令执行成功。如果命令失败,则退出状态为非零。
下面表格中是返回值对应着退出状态的解释:
| 返回值 | 退出状态 |
|---|---|
| 0 | 成功 |
| 非0状态 | 失败 |
| 2 | 用法不正确 |
| 126 | 不是可执行文件 |
| 127 | 没有找到指令 |
$?特殊变量
shell中的变量名$?是一个特殊的内置变量,可以获取最后一次执行命令的退出状态。
$?返回函数中最后一次执行命令的退出状态。$?返回脚本中最后一次执行命令的退出状态。以下exit_status.sh脚本显示了几种退出状态:
[root@localhost scripts]# vim exit_status.sh #! /bin/bash echo -e "Successful execution" echo -e "=====================" echo "hello world" # 退出状态为0,因为命令执行是成功的。 echo "Exit status" $? echo . echo -e "Incorrect usage" echo -e "=====================" ls --option # 使用了错误的用法,所以退出状态为2。 echo "Exit status" $? echo . echo -e "Command Not found" echo -e "=====================" bashscript # 退出状态为127,因为该脚本或者命令不存在。 echo "Exit status" $? echo . echo -e "Command is not an executable" echo -e "=============================" touch execution.sh ls -l execution.sh ./execution.sh # 退出状态为126,因为该文件没有执行权限。 echo "Exit status" $? echo . echo -e "Custom status" echo -e "=====================" function test1(){ if [ ! -x "./execution.sh" ]; then echo ""./execution.sh" no execute permission!!" return 66 fi } test1 # 退出状态为66,函数test1中判断文件是否不存在,不存在就返回echo语句,并定义了返回值。 echo "Exit status" $?
下面是执行结果后,返回的各种退出状态。
本文来源:www.lxlinux.net/9104.html,若引用不当,请联系修改。
服务器购买/咨询热线:15637009171或15617636856
本文链接:http://43.134.181.216/jishuzhichiyuweihu/11935.html