众所周知,简单的if
语句如下:
如果测试命令;则后续命令;fi
然后医生说:
执行 TEST-COMMAND 列表,如果其返回状态为零,则执行 CONSEQUENT-COMMANDS 列表
这是否意味着 TEST-COMMAND 的返回状态使用以下规则转换为布尔值 true/false:
返回状态 - 0 -> true
返回状态 - 1 -> false
然后使用 if 语句来确定采取什么操作?
答案1
是的。例如:
$ exitwith() { return $1; }
$ for stat in {0..10}; do
> if exitwith $stat; then
> echo "An exit status of $stat is considered true"
> else
> echo "An exit status of $stat is considered false"
> fi
> done
An exit status of 0 is considered true
An exit status of 1 is considered false
An exit status of 2 is considered false
An exit status of 3 is considered false
An exit status of 4 is considered false
An exit status of 5 is considered false
An exit status of 6 is considered false
An exit status of 7 is considered false
An exit status of 8 is considered false
An exit status of 9 is considered false
An exit status of 10 is considered false
但实际上它要比这稍微复杂一些,因为退出状态是一个 8 位无符号整数,其范围只能是 0 到 255;超出该范围的值将以 256 为模减少到该范围内:
$ for stat in -2 -1 255 256 257; do
> if exitwith $stat; then
> echo "An exit status of $stat (actually $?) is considered true"
> else
> echo "An exit status of $stat (actually $?) is considered false"
> fi
> done
An exit status of -2 (actually 254) is considered false
An exit status of -1 (actually 255) is considered false
An exit status of 255 (actually 255) is considered false
An exit status of 256 (actually 0) is considered true
An exit status of 257 (actually 1) is considered false