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 "
}

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