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语句应该使用双圆括号。

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s