Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - Why does ((count++)) return 1 exit code first time run

I have no idea why the indicated line below is returning 1 while the subsequent executions of ((count++)) are returning 0.

[me@server ~]$ count=0
[me@server ~]$ echo $?
0
[me@server ~]$ count++
-bash: count++: command not found
[me@server ~]$ (count++)
-bash: count++: command not found
[me@server ~]$ ((count++))
[me@server ~]$ echo $?
1 <------THIS WHY IS IT 1 AND NOT 0??
[me@server ~]$ ((count++))
[me@server ~]$ echo $?
0
[me@server ~]$ ((count++))
[me@server ~]$ echo $?
0
[me@server ~]$ echo $count
3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the excerpt from the help let page,

If the last ARG evaluates to 0, let returns 1; 0 is returned otherwise.

Since the operation is post-increment, ((count++)), for the very first time 0 is retained, hence returning 1

Notice, the same does not happen for pre-increment ((++count)), since the value is set to 1, on the first iteration itself.

$ unset count
$ count=0
$ echo $?
0
$ ++count
-bash: ++count: command not found
$ echo $?
127
$ ((++count))
$ echo $?
0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...