| 〖正天时代〗HTC Touch2/T3333◆原厂原配 | |
1690.0元 |
Bash Shell的退出状态 |
在上篇 bash 脚本编程文章的介绍中,我们知道所谓脚本就是包含了一组能被特定的 shell 解释并执行的命令集合。在这片文章中,我们会了解 shell 命令以及它们的内部 (internals) 。
命令就是一组单词序列的组合。第一个单词是将被执行的命令,剩下的单词将作为参数传递给这个命令。在这里参数 (arguments) 可以是选项 (options) ,也可以是参数值 (parameters) 。
在命令行中执行的命令有些是 shell 命令,比如 ls,lpr 以及 grep 命令。
$ ls -alF $ lpr filename $ grep "string" filename |
Shell 命令的退出状态
命令的返回值就是它的退出状态,如果该命令被信号 n 终止,那么它的退出状态就是 128+n 。退出状态用来检查命令是否被成功执行。如果状态为 0 ,那么该命令执行成功。如果该命令执行失败,那么退出状态为非零。
Exit Value | Exit Status |
0(Zero) | Success |
Non-zero | Failure |
2 | Incorrect usage |
127 | Command Not Found |
126 | Not an executable |
Shell 变量 $?
Shell变量$?是一个特殊的内建变量,它存储的是最后一个被执行的命令的退出状态。
1. 当shell函数执行后,$?返回函数体内最后一个命令的退出状态。
2. 当shell脚本执行后,$?返回脚本内最后一个命令的退出状态。
Shell 命令退出状态实例
下面的exitstatus.sh脚本显示不同shell命令的退出状态。
$ cat exitstatus.sh #! /bin/bash echo -e "Successful execution" echo -e "=====================" echo "hello world" # Exit status returns 0, because the above command is a success. echo "Exit status" $? echo -e "Incorrect usage" echo -e "=====================" ls --option # Incorrect usage, so exit status will be 2. echo "Exit status" $? echo -e "Command Not found" echo -e "=====================" bashscript # Exit status returns 127, because bashscript command not found echo "Exit status" $? echo -e "Command is not an executable" echo -e "=============================" ls -l execution.sh ./execution.sh # Exit status returns 126, because its not an executable. echo "Exit status" $? |
现在,执行上面的exitstatus.sh脚本,查看不同的退出状态。
$ bash exitstatus.sh Successful execution ===================== hello world Exit status 0 Incorrect usage ===================== ls: unrecognized option `--option' Try `ls --help' for more information. Exit status 2 Command Not found ===================== exitstaus.sh: line 15: bashscript: command not found Exit status 127 Command is not an executable ============================= -rw-r--r-- 1 root root 659 Mar 9 13:36 execution.sh exitstatus.sh: line 21: ./execution.sh: Permission denied Exit status 126 |
| 〖正天时代〗HTC Touch2/T3333◆原厂原配 | |
1690.0元 |