test
image
示例:
$ touch a.txt
$ test -e a.txt;echo $?
0 # 測試成功啄刹,命令返回值為 0
$ test -e s.txt;echo $?
1 # 測試失敗誓军,命令返回值為 非 0
$ test -f a.txt;echo $?
0
$ test -d a.txt;echo $?
1
image
示例:
$ test -r a.txt; echo $?
0
$ test -x a.txt; echo $?
1
$ test -w a.txt; echo $?
0
$ test -u a.txt; echo $? # 判斷 a.txt 文件是否具有 SUID 屬性
1
$ cat a.txt # 查看 a.txt 捷雕,此文件內(nèi)容為空
$ test -s a.txt; echo $? # 判斷 a.txt 文件中有內(nèi)容
1 # 命令返回值為 1 ,說明文件中沒有內(nèi)容
$ echo "123" > a.txt
$ test -s a.txt; echo $?
0
image
示例:
$ touch b.txt
$ ls -l a.txt
-rw-r--r-- 1 shark staff 4 12 17 22:59 a.txt
$ ls -l b.txt
-rw-r--r-- 1 shark staff 0 12 17 23:05 b.txt
$ test a.txt -nt b.txt; echo $? # 判斷 a.txt 是否比 b.txt 新
1 # 返回 1, 表示判斷表達(dá)式不成立
$ test b.txt -nt a.txt; echo $?
0
image
$ test a.txt -ef a-hard.txt; echo $?
0
image
示例:
$ test 10 -eq 20; echo $?
1
$ n1=10
$ n2=20
$ test $n1 -eq $n2; echo $?
1
$ test $n1 -lt $n2; echo $?
0
$ test $n1 -ne $n2; echo $?
0
c 風(fēng)格的判斷
image
image
注意:
這里的string
可以是實(shí)際的字符串壹甥,也可以是一個變量
這里說的字符串是否為0
的意思是字符串的長度是否為 0
示例
$ test -z ''; echo $? # 空字符串
0
$ test -z ' '; echo $? # 含有一個空格的字符串
1
$ test ! -z ' '; echo $? # 判斷含有一個空格的字符串救巷,其長度為非 0 的字符串, 空格也算是字符串。
0
$ test -z ${name}; echo $? # 變量未定義句柠,shell 中認(rèn)為其長度為 0
0
$ name=shark
$ test -z ${name}; echo $?
1
$ age='' # 定義變量浦译,并且賦值為空字符串
$ test -z ${age}; echo $? # shell 中,被賦值為空字符串的變量長度也為 0
0
注意:
再次強(qiáng)調(diào)一下, 在 shell 中溯职,以下兩種情況囤捻,變量的長度均視為
0
- 1.變量未定義
- 變量定義了虎囚,但賦值為空字符串捂贿,比如
a=''
,b=""
[root@kube-master script]# name=shark
[root@kube-master script]# age=shark
[root@kube-master script]# test $name == $age ;echo $?
0
[root@kube-master script]# test $name != $age ;echo $?
1
[root@kube-master script]#
image
示例
image
判斷符號 []
[ -z "${HOME}" ] ; echo $?
必須要注意中括號的兩端需要有空白字符來分隔喔泛释! 假設(shè)我空白鍵使用“□”符號來表示祝拯,那么鹰贵,在這些地方你都需要有空白鍵:
image
- 在中括號 [] 內(nèi)的每個元素之間都需要用空格來分隔碉输;
- 在中括號內(nèi)的變量敷钾,最好都以雙引號括號起來阻荒;
錯誤示范
# 定義變量
name="shark ops"
# 開始測試值是否相等
[ ${name} == "xiguatian" ]
會報如下錯誤信息:
bash: [: too many arguments
之前的錯誤寫法 [ ${name} == "xiguatian" ]
的侨赡,會變成這樣 [ shark ops == "xiguatian" ]
正確寫法應(yīng)該寫成這樣 [ "${name}" == "xiguatian" ]
的, 會變成這樣 [ "shark ops" == "xiguatian" ]
作者:運(yùn)維開發(fā)_西瓜甜
鏈接:http://www.reibang.com/p/ea61be326568
來源:簡書
簡書著作權(quán)歸作者所有齐婴,任何形式的轉(zhuǎn)載都請聯(lián)系作者獲得授權(quán)并注明出處眨攘。