#!/bin/bash
echo "Enter a number"
read num
i=2
res=true
while [ $i -le $num ]
do
if [ `expr $num%$i` -eq 0 ]
then
res=false
fi
i=`expr $i + 1`
done
echo "$res"
当与echo....一起使用时,if语句中的expr $num%$i
给出%为什么如此?
Enter a number
6
./4.sh: line 8: [: 6%2: integer expression expected
./4.sh: line 8: [: 6%3: integer expression expected
./4.sh: line 8: [: 6%4: integer expression expected
./4.sh: line 8: [: 6%5: integer expression expected
./4.sh: line 8: [: 6%6: integer expression expected
true
为什么exp不是按照模运算符
求值简单的解决方案,用空格分隔参数和运算符,例如:
num=6
i=2
# wrong
$ if [ `expr $num%$i` -eq 0 ]; then echo 'equal'; fi
-bash: [: 6%2: integer expression expected
# right
$ if [ `expr $num % $i` -eq 0 ]; then echo 'equal'; fi
equal
# or
$ if [ $(( num % i )) -eq 0 ]; then echo 'equal'; fi
equal
# or
$ if (( num % i == 0 )); then echo 'equal'; fi
equal