条件语句未按预期工作

Conditional statement not working as expected

我在 kubuntu 14.04 上使用 Konsole。

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

#!/bin/bash
ct=0
begin=
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 次迭代增加一次,但它在循环的每次迭代中都在增加。我做错了什么?

您想用

进行测试
if [ $(expr $cr % 3) = 0 ]; then ...

因为这个

[ $ct%3==0 ]

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

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

#!/bin/bash

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