Bash中如何进行条件测试:
1. 整数测试
2. 字符串测试
3. 文件测试
测试的表达式: 只有在测试条件中才使用[ ],并且前后要有空格,命令不使用
[ condition (条件) ]
[[ condition ]]
test condition
A.B [ $A -eq $B ]
整数测试:
-eq 左边等于右边(equal)
-ne 左右是否不等于(not equal)
-gt 左边大于右边(greater than)
-lt 左边小于右边(less than)
-ge 左边大于或等于右边(greater than or equal)
-le 左边小于或等于右边(less than or equal)
[ $A -ge $B ] 记得中括号前后要有空格
字符串测试:
== 字符串是否相等
!= 字符串不等于
-z 字符串是否为空 字符串要加双号
# [ -z "$A" ] && echo " is null" || echo "is not null"
-n 字符串是否不为空,不为空为真,为空为假
# [ -z "$A" ] && echo "A is mull." || echo "A is not null."
A is mull.
文件测试:
-e FILE 文件是否存在,存在为真,不存在为假
-f FILE 是否为普通文件
-d FILE 是否为目录
-h或-L FILE 是否为符号连接
-b FILE 是否为块文件
-c FILE 是否为字符设备
-S FILE 是否存在且为一个套接字(Socket)文件
-p FILE 是否为FIFO(pipe)文件
-r FILE 是否具有读权限
-w FILE 是否具有写权限
-x FILE 是否具有执行权限
-u FILE 是否存在且具有“SUID”的属性
-g FILE 是否存在且具有“SGID”的属性
-k FILE 是否存在且具有“Sticky bit”的属性
-s FILE 是否存在且具有“非空白文件”
# [ -d /tmp/test ] && echo "Diectory" || echo "Not"
Not
两个文件之间的比较:
-nt (newer than)判断file1是否比file2新
-ot (older than) 旧
-ef 判断file1与file2是否为同一文件,可用在判断hard link'上,主要意义在于判断两个文件是否均指向同一个inode
# test file1 -nt file2
多重条件判断:
-a 与的关系,两个条件同时成立
-o 或的关系,任何一个条件成立
! 非的关系,反向状态
# test -r filename -a -x filename