Linux shell編程 -test

test 命令的格式很是簡單shell

test condition bash

condition 是test命令要測試的一系列參數和值。當用在if-then 語句中時,test 命令看起來是這樣的測試

if test conditiondns

then字符串

commandsit

f iio

若是不寫test  命令的condition 部分,它會以非零的退出狀態碼退出,並執行else 語句塊table

 

bash shell 提供了另外一種條件測試方法,無需在if -then 語句中聲明testtest

if [condition]變量

then 

commands

f i

方括號定義了測試條件,注意第一個方括號以後和第二個方括號以前必須加上一個空格,不然就會報錯

test 命令能夠判斷三類條件:

  • 數值比較
  • 字符串比較
  • 文件比較

 

 

數值比較

比較 描述
n1 -eq n2 檢查n1 與n2  是否相等
n1 -ge n2 檢查n1是否大於或等於n2
n1 -gt n2 檢查n1是否大於 n2
n1 -le n2 檢查n1 是否小於等於n2
n1 -lt n2 檢查n1  是否小於n2
n1 -ne n2 檢查n1 是否不等於n2

字符串比較

比較 描述
str1=str2 檢查str1是否與str2 相等
str1!=str2 檢查str1是否和str2 不一樣
str1<str2 檢查str1是否比str2小
str1>str2 檢查str1是否比str2大
-n str1 檢查str1 的長度是否非0
-z  str1 檢查str1 的長度是否爲0

 

 

-n 和 -z 能夠檢查一個變量是否含有數據

$var1="zhangjunjie"

$var2="junjie"

if [-n $var1]

then

commands

 判斷var1 變量的長度是否非0.而它的長度正好非0.因此then 部分就被執行了

 

if [-z $var2]

then

commadns

-z  判斷var2 的長度是否爲0.而它的長度正好爲0,因此then部分就被執行了

相關文章
相關標籤/搜索