shell基礎命令--test命令

1.test命令

test = [ ]   ##[ ] 相當於test命令 
##判斷a和b的值是否相等
test "$a" = "$b" && echo yes || echo no
[ "$a" = "$b" ] && echo yes || echo no

2.test數字對比

= 等於
!= 不等於
-eq 等於
-ne 不等於
-le 小於等於
-lt 小於
-ge 大於等於
-gt 大於
##a的值爲1 b的值爲2
[root@rhel8 mnt]# [ "$a" = "$b" ] && echo yes || echo no
no     		##判斷a是否等於b
[root@rhel8 mnt]# [ "$a" != "$b" ] && echo yes || echo no
yes			##判斷a是否不等於b
[root@rhel8 mnt]# [ "$a" -eq "$b" ] && echo yes || echo no
no			##判斷a是否等於b
[root@rhel8 mnt]# [ "$a" -ne "$b" ] && echo yes || echo no
yes			##判斷a是否b不等於b
[root@rhel8 mnt]# [ "$a" -le "$b" ] && echo yes || echo no
yes			##判斷a小於等於b
[root@rhel8 mnt]# [ "$a" -lt "$b" ] && echo yes || echo no
yes			##判斷a是否小於b
[root@rhel8 mnt]# [ "$a" -ge "$b" ] && echo yes || echo no
no			##判斷a是否大於等於b
[root@rhel8 mnt]# [ "$a" -gt "$b" ] && echo yes || echo no
no			##判斷a是否大於b

3.test的條件關係

-a 並且
-o 或者
##判斷a的值是否爲10以內的整數
[ "$a" -gt 0  -a "$a" -le 10 ] && echo yes || echo no
[ "$a" -le 0 -o "$b" -gt 10 ] && echo no || echo yes

4.test對空的判定

-n nozero 判定內容不爲空
-z zero 判定內容爲空
[ -n "$a"  ]  && echo yes || echo no ##a的值不爲空輸出yes,否則輸出no
[ -z "$a"  ]  && echo yes || echo no ##a的值爲空輸出yes,否則輸出no

5.test對於文件的判定

-ef 文件節點號是否一致(硬鏈)
-nt 文件1是不是比文件2新
-ot 文件1是不是比文件2舊
-d 目錄
-S 套接字
-L 軟鏈接
-e 存在
-f 普通文件
-b 塊設備
-c 字符設備
#!/bin/bash
#file_check.sh 在執行時
#如果腳本後未指定檢測文件報錯“未指定檢測文件,請指定”
#如果腳本後指定文件不存在報錯“此文件不存在”
#當文件存在時請檢測文件類型並顯示到輸出中
[ -z "$1" ] &&{
	echo "未指定檢測文件,請指定"
	exit
}

[ -e "$1" ] ||{
	echo "$1 is not exist!"
	exit
}
[ -d "$1" ] &&{
	echo "$1 is directory"
}
[ -S "$1" ] &&{
	echo "$1 is socket"
}
[ -L "$1" ] &&{
	echo " $1 is link "
}
[ -f "$1" ] &&{
	echo " $1 is file "
}

[ -b "$1" ] &&{
	echo " $1 is block "
}

[ -c "$1" ] &&{
	echo " $1 is character device "
}

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