例子:
touch item01.txt
test -e item01.txt
echo $?
输出:0
一种解释:
(隐含前提:习惯上我们会更关注“0”或“非0”的划分)
在bash语言中,0, 1 只表示返回状态码。
而作为状态码,我们希望“成功”是一种返回,“失败”则有多种返回,对应多种出错信息。
而0只有一种类型;如果返回非零数字,则有1~255,可以表示各种错误。一些常见的错误码如下:
Table 1. Reserved Exit Codes
状态码 | 描述 |
0 | 命令成功结束 |
1 | 通用未知错误 |
2 | 误用Shell命令 |
126 | 命令不可执行 |
127 | 没找到命令 |
128 | 无效退出参数 |
128+x | Linux信号x的严重错误 |
130 | 命令通过Ctrl+C控制码越界 |
According to the above table, exit codes 1 - 2, 126 - 165, and 255 [1] have special meanings, and should therefore be avoided for user-specified exit parameters. Ending a script with exit 127 would certainly cause confusion when troubleshooting (is the error code a "command not found" or a user-defined one?). However, many scripts use an exit 1 as a general bailout-upon-error. Since exit code 1 signifies so many possible errors, it is not particularly useful in debugging.
[1] | Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225). |
补充
Q: 既然如此,shell中可以将 0, 1 作为条件写入判断语句中吗?
A: 判断语句中不管写什么数字都返回真。因此shell中 while[ 1 ]与while[ 0 ]循环都是用真。
注:shell脚本中的[ ]条件语句两端必须有空格 即[空格conditon空格]
REF:
Advanced Bash-Scripting Guide: Appendix E. Exit Codes With Special Meanings http://tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF
shell学习笔记 shell脚本 0 1 和真假 https://blog.csdn.net/shGray/article/details/101354337
# 这周唯二的空课,快乐 :D