Bash 数值比较

示例

数值比较使用-eq运算符和朋友

if [[ $num1 -eq $num2 ]]; then
  echo "$num1 == $num2"
fi
if [[ $num1 -le $num2 ]]; then
  echo "$num1 <= $num2"
fi

有六个数字运算符:

  • -eq 等于

  • -ne 不相等

  • -le 小于或等于

  • -lt 少于

  • -ge 大于或等于

  • -gt 比...更棒

请注意,里面的<and>运算符[[ … ]]比较字符串,而不是数字。

if [[ 9 -lt 10 ]]; then
  echo "9 is before 10 in numeric order"
fi
if [[ 9 > 10 ]]; then
  echo "9 is after 10 in lexicographic order"
fi

两侧必须是用十进制(或用前导零开头的八进制)写的数字。或者,使用((…))算术表达式语法,该语法以类似于C / Java /…的语法执行整数计算。

x=2
if ((2*x == 4)); then
  echo "2 times 2 is 4"
fi
((x += 1))
echo "2 plus 1 is $x"