这段代码没有任何失败,但是如果使用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

我认为这足以解释任何人都会理解这个问题,但因为我需要添加更多的文本,以提交这一点,我写这行。

最佳答案

i++将返回i的旧值,因此第一个counter++将返回0,这在bash的算术上下文中意味着false。
(参考:https://en.wikipedia.org/wiki/Increment_and_decrement_operators

关于linux - 为什么当counter == 0时((counter++))失败?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47219471/

10-14 08:53