基本语法
(1)test condition
(2)[ condition ] (注意 condition 前后要有空格)
注意:条件非空即为 true,[ 123 ]返回 true,[ ] 返回 false
[root@pwd ~]# a=zhangsan
[root@pwd ~]# echo $a
zhangsan
[root@pwd ~]# test $a = zhangsan
[root@pwd ~]# echo $?
0
[root@pwd ~]# test $a = lisi
[root@pwd ~]# echo $?
1
[root@pwd ~]#
常见的判断条件
(1)两个整数之间比较
-eq 等于(equal)
-ne 不等于(not equal)
-lt 小于(less than)
-le 小于等于(less equal)
-gt 大于(greater than)
-ge 大于等于(greater equal)
[root@pwd ~]# [ 2 -eq 2 ]
[root@pwd ~]# echo $?
0
[root@pwd ~]# [ 2 -ne 2 ]
[root@pwd ~]# echo $?
1
[root@pwd ~]# [ 2 -lt 2 ]
[root@pwd ~]# echo $?
1
[root@pwd ~]# [ 2 -le 2 ]
[root@pwd ~]# echo $?
0
[root@pwd ~]# [ 2 -gt 2 ]
[root@pwd ~]# echo $?
1
[root@pwd ~]# [ 2 -ge 2 ]
[root@pwd ~]# echo $?
0
[root@pwd ~]#
注:如果是字符串之间的比较 ,用等号“=”判断相等;用“!=”判断不等。
(2)按照文件权限进行判断
-r 有读的权限(read)
-w 有写的权限(write)
-x 有执行的权限(execute)
[root@pwd shdir]# touch test
[root@pwd shdir]# ls -l
-rw-r--r-- 1 root root 0 May 13 21:57 test
[root@pwd shdir]# su test01
[test01@pwd shdir]$ [ -r test ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -w test ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$ [ -x test ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$
(3)按照文件类型进行判断
-e 文件存在(existence)
-f 文件存在并且是一个常规的文件(file)
-d 文件存在并且是一个目录(directory)
[test01@pwd shdir]$ [ -e /etc/passwd ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -e /etc/passwd123 ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$ [ -f /etc/passwd ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -f test ]
[test01@pwd shdir]$ echo $?
0
[test01@pwd shdir]$ [ -d test ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$ [ -d /etc/passwd ]
[test01@pwd shdir]$ echo $?
1
[test01@pwd shdir]$
(4)多条件运算
&& 多条件且 || 多条件或
[test01@pwd shdir]$ [ 18 -lt 20 ] && echo "判定成功" || echo "判定失败"
判定成功
[test01@pwd shdir]$ [ 18 -gt 20 ] && echo "判定成功" || echo "判定失败"
判定失败
[test01@pwd shdir]$