shell中的test测试命令

test的定义

Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试

格式

test 测试条件 或 [ 测试条件 ]

注意事项:中括号两边要有空格
test和[ ]用哪个都是一样效果

测试条件

整数比较

-eq 等于(equal) [ $a -eq $b ]
-ne 不等于(not equal) [ $a -ne $b ]
-gt 大于(greater than) [ $a -gt $b ]
-lt 小于(lesser than) [ $a -lt $b ]
-le 小于等于(lesser or equal) [ $a -le $b ]
-ge 大于等于(greater or equal) [ $a -ge $b ]

[root@haha ~]# Unum=$(who | wc -l)
[root@haha ~]# [ $Unum -gt 0 ] && echo "login user :$Unum"
login user :1
设置一个变量
如果有用户登录,就打印出登录的用户数量
[root@haha ~]# available_mem=`free -m | grep -i "mem" |
 awk '{print $7}'`
[root@haha ~]# [ $available_mem -lt 2048 ] && echo ${
    
    available
_mem}MB
714MB
判断当前主机可用内存大小,当低于2048时输出具体数值

字符串比较

== 判断两个字符串是否相等 [ “ a ” = = “ a” == “ a==b” ]
!= 判断两个字符串是否不相等 [ “ a ” ! = “ a” != “ a!=b” ]
-z 字符串 判断字符串是否为空 [ -z “$a” ]

-n 字符串判断字符串是否不为空 [ -n “$a” ]
str1 > str2 判断字符串str1是否大于str2 [ “str1” > “str2” ]
str1 < str2 判断字符串str1是否小于str2 [ “str1” < “str2” ]

[root@haha ~]# [ -n "abc" ] && echo 1 || echo 0
1
[root@haha ~]# [ -n " " ] && echo 1 || echo 0
1
[root@haha ~]# [ -n "" ] && echo 1 || echo 0
0
[root@haha ~]# [ -z "abc" ] && echo 1 || echo 0
0
[root@haha ~]# [ -z "" ] && echo 1 || echo 0
1

文件比较

-e存在(exist) [ -e file ]
-r可读(read) [ -r file ]
-w可写(write) [ -w file ]
-x可执行(execute) [ -x file ]
-s存在字符 [ -s file ]
-d存在且为目录(directory) [ -d file ]
-f存在且为普通文件(file) [ -f file ]
-c存在且为字符型特殊文件 [ -c file ]
-b存在且为块特殊文件(block) [ -b file ]
-nt检查file1是否比file2新(new time) [ file1 -nt file2 ]
-ot 检查file1是否比file2旧(old time) [ file1 -nt file2 ]

[root@haha ~]# [ -f haha.txt ] && echo "haha is exist" || ech
o "haha is'n exist"
haha is exist

存在haha.txt这个普通文件,就输出||左侧内容,否则输出右侧

[root@haha ~]# [ -d haha ] && echo "haha is exist" || echo "ha
ha isn't exist"
haha isn‘t exist
[root@haha ~]# [ ! -f xxx ] && echo true || echo false
true

!表示取反的意思,即否定,感叹号和参数中间是有空格的不存在或者
xxx不是普通文件即为真

逻辑操作符

[[ ]]是扩展test命令,&& 、|| 、> 、<像这样符号可以用在[[ ]]中,不能用在[ ]中
在[]和test中:
-a 与,两条件都为真,条件满足
-o 或,两条件一个为真,条件满足
! not,取反

在[[]]和(())中
&& 与,两条件都为真,条件满足
|| 或,两条件一个为真,条件满足
! not,取反

[root@haha ~]#  [  -f haha -a -x haha.sh  ] && echo “1|| ec
ho “00

##haha是不是普通文件与 haha.sh是不是可执行的文件,需要同时
为真,才输出1

[root@haha ~]# [[  -f haha || -x haha.sh  ]] && echo “1|| ec
ho “01

##haha或者haha.sh其中成立一项,就输出1

猜你喜欢

转载自blog.csdn.net/weixin_52441468/article/details/112319871