Scripting

比較 bash 變數以查看是否可被 5 整除

  • February 12, 2018

這是我的程式碼;我想$COUNTER多次比較各種。

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

沒關係,但我希望它在動態時間5,10,15,20等情況下這樣做。

各種評論的結論似乎是對原始問題的最簡單答案是

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

您可以使用模算術運算符執行此操作:

#!/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 的倍數:

loop.sh

#!/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

引用自:https://unix.stackexchange.com/questions/423389