在Linux中,关系运算符用于比较两个值
等于(==):检查两个值是否相等。 示例:
if [ $num1 == $num2 ]; then
echo "Numbers are equal."
else
echo "Numbers are not equal."
fi
不等于(!=):检查两个值是否不相等。 示例:
if [ $num1 != $num2 ]; then
echo "Numbers are not equal."
else
echo "Numbers are equal."
fi
大于(>):检查左边的值是否大于右边的值。 示例:
if [ $num1 -gt $num2 ]; then
echo "Number 1 is greater than Number 2."
else
echo "Number 1 is not greater than Number 2."
fi
小于(<):检查左边的值是否小于右边的值。 示例:
if [ $num1 -lt $num2 ]; then
echo "Number 1 is less than Number 2."
else
echo "Number 1 is not less than Number 2."
fi
大于等于(>=):检查左边的值是否大于或等于右边的值。 示例:
if [ $num1 -ge $num2 ]; then
echo "Number 1 is greater than or equal to Number 2."
else
echo "Number 1 is not greater than or equal to Number 2."
fi
小于等于(<=):检查左边的值是否小于或等于右边的值。 示例:
if [ $num1 -le $num2 ]; then
echo "Number 1 is less than or equal to Number 2."
else
echo "Number 1 is not less than or equal to Number 2."
fi
注意:在使用关系运算符时,请确保在变量周围使用双括号([[ ]]
)以避免潜在的错误。例如:
if [[ $num1 -eq $num2 ]]; then
echo "Numbers are equal."
else
echo "Numbers are not equal."
fi