![得到“预期的整数表达式”,我不明白为什么](https://linux22.com/image/188026/%E5%BE%97%E5%88%B0%E2%80%9C%E9%A2%84%E6%9C%9F%E7%9A%84%E6%95%B4%E6%95%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E2%80%9D%EF%BC%8C%E6%88%91%E4%B8%8D%E6%98%8E%E7%99%BD%E4%B8%BA%E4%BB%80%E4%B9%88.png)
#!/usr/bin/bash
for (( i=0; i<=10; i++ ))
do
if [ "$i" -eq 3 ] || [ "$1" -eq 7 ]
then
continue
fi
echo "$i"
done
运行这个时,我得到
file: line 4: [: : integer expression expected
0
file: line 4: [: : integer expression expected
1
file: line 4: [: : integer expression expected
2
file: line 4: [: : integer expression expected
4
file: line 4: [: : integer expression expected
5
file: line 4: [: : integer expression expected
6
file: line 4: [: : integer expression expected
7
file: line 4: [: : integer expression expected
8
file: line 4: [: : integer expression expected
9
file: line 4: [: : integer expression expected
10
...我不明白为什么。
答案1
如果您不带参数调用脚本,则命令:
[ "$1" -eq 7 ]
将评估为:
[ "" -eq 7 ]
这是一个错误,就像-eq
数字运算符一样:它需要两个整数作为操作数;空字符串不是整数。
如果您不希望使用参数调用脚本,而是希望比较i
to的值7
,您可能需要:
[ "$i" -eq 7 ]
而不是:
[ "$1" -eq 7 ]