28. 数字比较
在开始讨论if
条件、for
循环和while
循环之前,让我们了解可以在if
语句的[ ]
和test
命令中使用哪些运算符进行数字和字符串比较。
要比较数字(整数),请使用以下运算符。
运算符 | 描述 |
---|---|
-eq |
相等 |
-ne |
不相等 |
-gt |
大于 |
-ge |
大于等于 |
-lt |
小于 |
-le |
小于等于 |
以下示例演示如何在if
语句中使用数字比较运算符。
$ cat operators-integer.sh
total=${1}
if [ $total -eq 100 ]; then
echo "-eq: total is equal to 100"
fi
if [ $total -ne 100 ]; then
echo "-ne: total is NOT equal to 100"
fi
if [ $total -lt 100 ]; then
echo "-lt: total is less than 100"
fi
if [ $total -gt 100 ]; then
echo "-gt: total is greater than 100"
fi
if [ $total -le 100 ]; then
echo "-le: total is less than or equal to 100"
fi
if [ $total -ge 100 ]; then
echo "-le: total is greater than or equal to 100"
fi
通过传递如下所示的参数来执行上述 shell 脚本,以查看各种测试条件如何工作:
$ ./operators-integer.sh 80
-ne: total is NOT equal to 100
-lt: total is less than 100
-le: total is less than or equal to 100