gpt4 book ai didi

linux - 为什么 ((counter++)) 在 counter == 0 时失败?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:37 26 4
gpt4 key购买 nike

此代码不会给出任何失败,但如果您使用 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++)) 在 counter == 0 时失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47219471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com