为什么 a=0; 让a++返回退出代码1?

l0b*_*0b0 17 bash ksh arithmetic

尝试一下:

$ a=0
$ let a++
$ echo $?
1 # Did the world just go mad?
$ echo $a
1 # Yes, it did.
$ let a++
$ echo $?
0 # We have normality.
$ echo $a
2
Run Code Online (Sandbox Code Playgroud)

对比一下:

$ b=0
$ let b+=1
$ echo $?
0
Run Code Online (Sandbox Code Playgroud)

这(来自Sirex):

$ c=0
$ let ++c
$ echo $?
0
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

$ bash --version
GNU bash, version 4.1.5(1)-release (x86_64-pc-linux-gnu)
Run Code Online (Sandbox Code Playgroud)

l0b*_*0b0 22

来自help let

Exit Status:
If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise..
Run Code Online (Sandbox Code Playgroud)

由于var++-Increment,我想最后一个参数评估为零。微妙的...

一个可能更清楚的说明:

$ let x=-1 ; echo x=$x \$?=$?
x=-1 $?=0
$ let x=0 ; echo x=$x \$?=$?
x=0 $?=1
$ let x=1 ; echo x=$x \$?=$?
x=1 $?=0
$ let x=2 ; echo x=$x \$?=$?
x=2 $?=0
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这对我有帮助。- 我不会再浪费时间问:“为什么?” (2认同)