当计数器== 0时,为什么((计数器++))失败?

时间:2017-11-10 09:26:17

标签: linux bash

此代码不会导致任何失败,但如果使用counter ++,则第一次迭代失败。

parameters="one two three"  
counter=0

  for option in $parameters
  do
    eval $option=${args[$counter]}
    ((counter = counter + 1)) # If you do ((counter++)) it fails the first iteration, weird.
    echo $option $?
  done

这就是我的意思:

ulukai@computer:~$ bash -x test.sh 
+ parameters='one two three'
+ counter=0
+ for option in '$parameters'
+ eval one=
++ one=
+ (( counter++ ))
+ echo one 1
one 1
+ for option in '$parameters'
+ eval two=
++ two=
+ (( counter++ ))
+ echo two 0
two 0
+ for option in '$parameters'
+ eval three=
++ three=
+ (( counter++ ))
+ echo three 0
three 0
ulukai@computer:~$ vi test.sh
ulukai@computer:~$ bash -x test.sh 
+ parameters='one two three'
+ counter=0
+ for option in '$parameters'
+ eval one=
++ one=
+ (( counter=counter+1 ))
+ echo one 0
one 0
+ for option in '$parameters'
+ eval two=
++ two=
+ (( counter=counter+1 ))
+ echo two 0
two 0
+ for option in '$parameters'
+ eval three=
++ three=
+ (( counter=counter+1 ))
+ echo three 0
three 0

我认为这对于理解这个问题的人来说足够解释,但是因为我需要添加更多文本才能提交这个,我正在写这一行。

1 个答案:

答案 0 :(得分:2)

i++将返回i的旧值,因此第一个counter++将返回0,这意味着在Bash的算术上下文中为FALSE。

(参考:https://en.wikipedia.org/wiki/Increment_and_decrement_operators