[Bash基础] 0表示真,1表示假 + 解释

例子:

touch item01.txt
test -e item01.txt
echo $?

输出:0

一种解释:

(隐含前提:习惯上我们会更关注“0”或“非0”的划分)

在bash语言中,0, 1 只表示返回状态码。

而作为状态码,我们希望“成功”是一种返回,“失败”则有多种返回,对应多种出错信息。

而0只有一种类型;如果返回非零数字,则有1~255,可以表示各种错误。一些常见的错误码如下:

Table 1. Reserved Exit Codes

状态码描述
0命令成功结束
1通用未知错误
误用Shell命令
126命令不可执行
127没找到命令
128无效退出参数
128+xLinux信号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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值