linuxSHELL學習之數字比較、字符串比較

1、test

test提供一種檢測if-then語句中不同條件的方法,如果test命令中列出的條件評估值爲true,test
命令以0
推出狀態碼退出。
if test condition
then 
   commands
fi
test命令提供3類條件的評估:數值比較、字符比較、文件比較
數值比較:
n1 -eq n2檢查n1是否等於n2         n1 -le n2檢查n1是否小於等於n2
n1 -ge n2檢查n1是否大於等於n2     n1 -lt n2檢查n1是否小於n2
n1 -gt n2檢查n1是否大於n2         n1 -ne n2檢查n1是否不等於n2
[root@t1 ~]# cat t1.sh 
#!/bin/bash
#using numeric test comparisons
var1=10
var2=11
if [ $var1 -lt 5 ]   #注意這裏的test與“[”和“]”之間必須要有空格,否則會報錯的。
then
  echo "the test value $var1 is greater than 5"
fi

if [ $var1 -eq $var2 ]  #注意這裏的test與“[”和“]”之間必須要有空格
then
  echo "the values are equal"
else
  echo "the values are different"
fi

[root@t1 ~]# ./t1.sh 
the values are different
字符串比較:
str1 = str2檢查str1與str2是否相同       str1 > str2檢查str1是否大於str2
str1 != str2檢查str1與str2是否不同      -n str1 檢查str1的長度是否大於0
str1 < str2檢查str1是否小於str2         -z str1 檢查str1的長度是否爲0
[root@t1 ~]# cat t2.sh  --判斷相等否
#!/bin/bash
#testing string eguality
testuser=root
if [ $USER = $testuser ]
then 
  echo "welcome $testuser"
fi
[root@t1 ~]# ./t2.sh 
welcome root
[root@t1 ~]# cat t3.sh   ---不等判斷
#!/bin/bash
#tesing string equality
testuser=oracle
if [ $testuser != root ]
then 
  echo "this is not $testuser"
else
  echo "welcome $testuser"
fi
[root@t1 ~]# ./t3.sh 
this is not oracle
字符串順序:
*大於和小於符號一定要轉義,否則shell會將他們當做重定向符號,將字符串值看作是文件名。
*大於和小於順序與在sort中不同
*test使用標準的ASCII排序,使用每個字母的ASCII數值來決定排序順序,sort命令使用爲當前系統語言設置定義的排序順序。對於英語來說,當前設置指定小寫字母排在大寫字母之前。
[root@t1 ~]# cat t4.sh 
#!/bin/bash
#testing string sort order
var1=Testing
var2=testing
if [ $var1 \> $var2 ]     ---使用標準的ASSCI進行的比較
then
 echo "$var1 is greater than $var2"
else
 echo "$var1 is less than $var2"
fi

[root@t1 ~]# ./t4.sh 
Testing is less than testing
**if [ -n var1 ]判斷var1是否爲非0值,if [ -z var1 ]判斷var1是否爲0
[root@t1 ~]# cat t5.sh 
#!/bin/bash
#testing string length
var1=testing
var2=''
if [ -n $var1 ] 
then
  echo "the string '$var1' is not emppty" 
else
  echo "the  string '$var1' is empty"
fi

if [ -z $var2 ]
then
  echo "the string '$var2' is empty"
else
  echo "the string '$var2' is not empty"
fi
if [ -z $var3 ]
then
  echo "the string '$var3' is empty"
else
  echo "the string '$var3' is not empty"
fi

[root@t1 ~]# ./t5.sh 
the string 'testing' is not emppty
the string '' is empty
the string '' is empty

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章