比较 bash 变量看是否能被 5 整除

比较 bash 变量看是否能被 5 整除

这是我的代码;我想$COUNTER多次比较。

if [ "$COUNTER" = "5" ]; then

没关系,但我想要这样做动态的5,10,15,20诸如此类的时间

答案1

各种评论的结论似乎是原始问题的最简单答案是

if ! (( $COUNTER % 5 )) ; then

答案2

您可以使用模算术运算符来执行此操作:

#!/bin/sh

counter="$1"
remainder=$(( counter % 5 ))
echo "Counter is $counter"
if [ "$remainder" -eq 0 ]; then
    echo 'its a multiple of 5'
else
    echo 'its not a multiple of 5'
fi

正在使用:

$ ./modulo.sh 10
Counter is 10
its a multiple of 5
$ ./modulo.sh 12
Counter is 12
its not a multiple of 5
$ ./modulo.sh 300
Counter is 300
its a multiple of 5

我还写了一个循环,可能就是您正在寻找的?这将循环遍历从 1 到 600 的每个数字并检查它们是否是 5 的倍数:

循环语句

#!/bin/sh
i=1
while [ "$i" -le 600 ]; do
        remainder=$(( i % 5 ))
        [ "$remainder" -eq 0 ] && echo "$i is a multiple of 5"
        i=$(( i + 1 ))
done

输出(缩短)

$ ./loop.sh
5 is a multiple of 5
10 is a multiple of 5
15 is a multiple of 5
20 is a multiple of 5
25 is a multiple of 5
30 is a multiple of 5
...
555 is a multiple of 5
560 is a multiple of 5
565 is a multiple of 5
570 is a multiple of 5
575 is a multiple of 5
580 is a multiple of 5
585 is a multiple of 5
590 is a multiple of 5
595 is a multiple of 5
600 is a multiple of 5

答案3

回答问题确切地正如目前所写的,忽略标题(已编辑)。

将变量中的整数与许多其他整数值进行比较,其中其他值是提前确定的(不清楚问题中“动态”的实际含义):

case "$value" in
    5|10|15|200|400|600)
        echo 'The value is one of those numbers' ;;
    *)
        echo 'The value is not one of those numbers'
esac

当然这也可以循环完成,

for i in 5 10 15 200 400 600; do
    if [ "$value" -eq "$i" ]; then
        echo 'The value is one of those numbers'
        break
    fi
done

但这使得处理案件变得更加困难$value困难不是在不使用某种标志的情况下在给定数字中找到:

found=0
for i in 5 10 15 200 400 600; do
    if [ "$value" -eq "$i" ]; then
        echo 'The value is one of those numbers'
        found=1
        break
    fi
done

if [ "$found" -eq 0 ]; then
    echo 'The value is not one of those numbers'
fi

或者,更清洁,

found=0
for i in 5 10 15 200 400 600; do
    if [ "$value" -eq "$i" ]; then
        found=1
        break
    fi
done

if [ "$found" -eq 1 ]; then
    echo 'The value is one of those numbers'
else
    echo 'The value is not one of those numbers'
fi

我个人会亲自去case ... esac实施。

相关内容