【问题标题】:Conditional statement not working as expected条件语句未按预期工作
【发布时间】:2015-02-03 07:25:47
【问题描述】:

我在 kubuntu 14.04 上使用 Konsole。

我想为这个 shell 脚本提供参数,并将它传递给一个命令。该代码基本上是一个无限循环,我希望每 3 次循环迭代增加一次内部命令的参数之一。忽略实际细节,这是我的代码的要点:

#!/bin/bash
ct=0
begin=$1
while :
    do
        echo "give: $begin as argument to the command"
        #actual command
        ct=$((ct+1))
        if [ $ct%3==0 ]; then
            begin=$(($begin+1))
        fi
    done

我希望begin 变量每 3 次迭代增加一次,但它在循环的每次迭代中都会增加。我做错了什么?

【问题讨论】:

    标签: linux shell conditional-statements konsole


    【解决方案1】:

    你想测试

    if [ $(expr $cr % 3) = 0 ]; then ...
    

    因为这个

    [ $ct%3==0 ]
    

    测试字符串$ct%3==0,参数替换后是否不为空。理解这一点的一个好方法是阅读test 的手册,并在给出 1、2、3 或更多参数时查看语义。在您的原始脚本中,它只看到一个参数,在我的脚本中它看到三个。空白在 shell 中非常重要。 :-)

    【讨论】:

      【解决方案2】:

      在 BASH 中,您可以完全利用 ((...)) 并像这样重构您的脚本:

      #!/bin/bash
      
      ct=0
      begin="$1"
      while :
      do
         echo "give: $begin as argument to the command"
         #actual command
        (( ct++ % 3 == 0)) && (( begin++ ))
      done
      

      【讨论】:

      • 我知道,但即使写了#!/bin/bash,我认为它没有使用 bash。这就是我使用 ct=$((ct+1)) 的原因,这是 askubuntu.com/questions/385528/… 中唯一有效的方法。
      猜你喜欢
      • 2020-10-23
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2017-10-27
      • 1970-01-01
      • 2012-08-16
      • 2020-03-11
      相关资源
      最近更新 更多