shell 條件測試總結

條件測試:推薦使用格式2


格式1:   test<測試表達式>              man test查看相關幫助

格式2:   [<測試表達式>]

格式3:   [[<測試表達式>]]



說明:在[[]]中可以使用通配符進行模式匹配 && ||  >  < 等操作符可以應用於[[]]中,但不能應用於[]中


[root@localhost ~]# test -f file && echo 1 || echo 0

0


[root@localhost ~]# touch file

[root@localhost ~]# test -f file && echo 1 || echo 0

1


[root@localhost ~]# test ! -f file && echo 1 || echo 0

0


[root@localhost ~]# arg="martin"

[root@localhost ~]# test -z "$arg" && echo 1  || echo 0

0


[root@localhost tools]# [ -f file ]&& echo 1 || echo 0

0


[root@localhost tools]# [[ -f file && -d dir ]]&& echo 1 || echo 0

0


文件測試操作符

-f  file

-d  dirrctory

-s  size   文件存在且不爲空則爲真

-e  exist  可以是文件也可以是目錄

-r  read

-w  write

-x  excute..

-L  link

f1 -nt f2    newer than 若文件f1比文件f2新則爲真

f1  -ot f2   older than


[root@localhost tools]# mkdir martin

[root@localhost tools]# [ -f martin ]&& echo 1 || echo 0

0

[root@localhost tools]# [ -d martin ]&& echo 1 || echo 0 

1

[root@localhost tools]# [ -e martin ]&& echo 1 || echo 0 

1



常用字符串測試操作符

-z  "字符串"   若長度爲0則爲真, -z 可以理解爲 zero

-n  "字符串"   若長度不爲0則爲真, -n 可以理解爲 no zero

"串1"="串2"    若串1等於串2則爲真,可使用== 代替=

"串1"!="串2"    若串1不於串2則爲真,但不能使用 !==代替 !=



字符串或字符串變量比較都要加雙引號再比較

字符串比較,比較符號兩端最好有空格,多參考系統腳本

[root@localhost tools]# sed -n '30,31p' /etc/init.d/network 

# Check that networking is up.

[ "${NETWORKING}" = "no" ] && exit 6


[root@localhost tools]# martin="hello"

[root@localhost tools]# [ "${martin}" = "hello" ]&& echo 1 || echo 0

1

[root@localhost tools]# [ "${martin}" = "hello123" ]&& echo 1 || echo 0

0


[root@localhost tools]# [ -n "abc" ]&& echo 1 || echo 0       

1

[root@localhost tools]# [ -n "" ]&& echo 1 || echo 0   

0


wKiom1gIumHgEW9nAAA_xDwA2ao164.png


[root@localhost tools]# [ 12 -eq 13 ]&&echo 1 || echo 0

0

[root@localhost tools]# [ 12 -lt 13 ]&&echo 1 || echo 0  

1

[root@localhost tools]# [ 12 -gt 13 ]&&echo 1 || echo 0 

0


[root@localhost tools]# [[ 12 > 13 ]]&&echo 1 || echo 0   

0

[root@localhost tools]# [[ 12 < 13 ]]&&echo 1 || echo 0 

1


邏輯操作符

在[]中使用的邏輯操作符       在[[]]中使用的邏輯操作符        說明

-a                               &&                          and

-o ||              or

!                                 !                          not   取反


[root@localhost tools]# [ -f "$f1" -a -f "$f2" ]&& echo 1 || echo 0

1


觀察系統腳本 nfs

# Source networking configuration.

[ -f /etc/sysconfig/network ] &&  . /etc/sysconfig/network


[root@localhost scripts]# sed -n '87,90p' /etc/init.d/nfs

[ "$NFSD_MODULE" != "noload" -a -x /sbin/modprobe ] && {

/sbin/modprobe nfsd

[ -n "$RDMA_PORT" ] && /sbin/modprobe svcrdma

}


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