Bash中的比较运算

像其他编程语言一样,Bash中也有基于数学符号的比较运算符。不过,它也可以用操作符来指明比较的类型(类似perl里面的比较操作符)。下面就给出了常用的比较运算方法。

#!/bin/bash

num1=8
num2=13

# Integer Comparison
if [ "$num1" -eq "$num2" ]; then echo "num1 is equal to num2"; fi
if [ "$num1" -ne "$num2" ]; then echo "num1 is not equal to num2"; fi
if [ "$num1" -gt "$num2" ]; then echo "num1 is greater than num2"; fi
if [[ "$num1" -ge "$num2" ]]; then echo "num1 is greater than or equal to num2"; fi
if [[ "$num1" -lt "$num2" ]]; then echo "num1 is less than to num2"; fi
if [[ "$num1" -le "$num2" ]]; then echo "num1 is less than or equal to num2"; fi

if (( "$num1" > "$num2" )); then echo "num1 is greater than num22"; fi
if (( "$num1" >= "$num2" )); then echo "num1 is greater than or equal to num2"; fi
if (( "$num1" < "$num2" )); then echo "num1 is less than to num2"; fi
if (( "$num1" <= "$num2" )); then echo "num1 is less than or equal to num2"; fi

# String Comparison
string1="bash1"
string2="bash2"
string3=""

if [ "$string1" = "$string2" ]; then echo "string1 is equal to string2"; fi
if [ "$string1" == "$string2" ]; then echo "string1 is equal to string2"; fi
if [ "$string1" != "$string2" ]; then echo "string1 is not equal to string2"; fi
if [[ "$string1" < "$string2" ]]; then echo "string1 is less than string2"; fi
if [[ "$string1" > "$string2" ]]; then echo "string1 is greater than string2"; fi
if [[ "$string3" == -z ]]; then echo "string1 is empty"; fi

以上示例罗列了常用的比较运算,要注意的是整数比较中,如果使用数学符号进行比较,if语句应该使用双圆括号。

作者: V

Web Dev

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Google photo

您的留言將使用 Google 帳號。 登出 /  變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s