Bash脚本循环?

时间:2017-05-07 13:40:44

标签: shell sh

这是一个来自之前考试的问题的脚本,我很困惑为什么我等于6而J等于9。有人可以详细说明吗?

下面是一个小的bash脚本。最终回声的输出是多少? 声明?展示你的工作。

 #!/bin/sh
i=0
for a in 9 8 7 6 5 4
do
j=1
for b in 1 2 3 4
do
let "j+=2"
done
let "i+=1"
done
echo "i=$i j=$j"

1 个答案:

答案 0 :(得分:3)

你应该写出代码;

#!/bin/sh

i=0
for a in 9 8 7 6 5 4   # <-  i gets incremented by 1 for each "step" here.
do 
    j=1
    for b in 1 2 3 4   # <-  j gets incremented by 2 for each "step" here.
    do 
        let "j+=2"     # <-  this is where j get incremented
    done
    let "i+=1"         # <-  this is where i get incremented
done
echo "i=$i j=$j"

因此,

  • j的起始值为1,并且增加+2(4次)= 9
  • 我的起始值为0,并且增加+1(6次)= 6