2020年8月13日 星期四

if 比較,字串與數值 的 operator 不同

ref: How to Compare Numbers, Strings and Files in Bash Shell Script

就是 if [ A ... 裡面 用的 operator,在數值字串會不一樣..
以上面的 link 中的說明:

if [2 -gt 3]
     then
     print "2 is greater"
     else
     print "2 is not greater"
fi
其他的 數值用 operator:
  • num1 -eq num2 : check if 1st number is equal to 2nd number
  • num1 -ge num2 : checks if 1st number is greater than or equal to 2nd number
  • num1 -gt num2 : checks if 1st number is greater than 2nd number
  • num1 -le num2 : checks if 1st number is less than or equal to 2nd number
  • num1 -lt num2 : checks if 1st number is less than 2nd number
  • num1 -ne num2 : checks if 1st number is not equal to 2nd number

字串的話...
name=linuxtechi
if [ $USER = $name ]
        then
                echo "User exists"
        else
                echo "User not found"
fi
  • var1 = var2 checks if var1 is the same as string var2
  • var1 != var2 checks if var1 is not the same as var2
  • var1 < var2 checks if var1 is less than var2
  • var1 > var2 checks if var1 is greater than var2
  • -n var1 checks if var1 has a length greater than zero
  • -z var1 checks if var1 has a length of zero

沒有留言:

張貼留言