shell条件判断详解
shell脚本中的条件判断
·
test 条件判断
test 命令
1. 文件类型与文件是否存在的判断
1.1 -e 判断文件或者目录是否存在
[root@taotaoplus ~]# test -e bbb.txt && echo '文件/目录已存在' || touch bbb.txt
[root@taotaoplus ~]# test -e bbb.txt && echo '文件/目录已存在' || touch bbb.txt
文件/目录已存在
[root@taotaoplus ~]# test -e bbb && echo '文件/目录已存在' || mkdir bbb
[root@taotaoplus ~]# test -e bbb && echo '文件/目录已存在' || mkdir bbb
文件/目录已存在
1.2 -f 判断是否为文件
[root@taotaoplus ~]# test -f bbb.txt && echo 'bbb.txt是文件'
bbb.txt是文件
[root@taotaoplus ~]# test -f bbb || echo 'bbb不是文件'
bbb不是文件
1.3 -d 判断是否为目录
1.4 -b 判断是否为block device装置
1.5 -c 判断是否为character device装置
1.6 -S 判断是否为socket文件
1.7 -P 判断是否为FIFO(pipe)文件
1.8 -L 判断是否为一个连接
2. 关于文件权限的判断
2.1 -r 判断是否 可读
2.2 -w 判断是否 可写
2.2 -x 判断是否 可执行
2.3 -u 判断是否具有 SUID 属性
2.4 -g 判断是否具有 SGID 属性
2.5 -k 判断是否具有 sticky bit 属性
2.6 -s 判断是否为 空白文件
3. 两个文件之间的比较,如 test file1 -nt file2
3.1 -nt file1是否比file2 新(new than)
3.2 -ot file1是否比file2 旧(old than)
3.3 -ef file1是否比file2 是否为同一文件
# 可用于 hard link 的判定,只要意义在于判定两个文件是否均指向同一个inode
4. 两个 整数 的判断
4.1 -eq 相等
4.2 -ne 不相等
4.3 -gt 大于
4.4 -lt 小于
4.5 -ge 大于等于
4.6 -le 小于等于
5. 判断字符串数据
5.1 test -z str 判定是否为空字符串,str为空返回true
5.2 test -n str 判定是否不为空字符串,str不为空返回true(PS;-n 可以省略)
5.3 test str1 = str2 判断是否相等
5.4 test str1 != str2 判断是否不相等
6. 多重条件判断
6.1 -a 两个同时成立(and)
test -r file -a -x file # 文件同时具有 r 权限和 x权限
6.2 -o 两个任一成立(or)
6.3 ! 取反
中括号条件判断
作用与test
相同
用的最多
前后必须用空格隔开:[ -n $name ]
1. 字符串判断
[ -z "str" ] str的长度为零,则为真 ,即判断是否为空,空即是真;
[ -n "str" ] str的长度非零,则为真 ,即判断是否为非空,非空即是真;
[ "str1" = "str2" ] 两个字符串相同,则为真;
[ "str1" != "str2" ] 两个字符串不相同,则为真;
[ "str1" ] 字符串不为空,则为真,与-n类似。
2. 文件判断
[ -e file ] file 存在,则为真。
[ -d DIR ] file 存在,且是一个目录,则为真。
[ -f file ] file 存在,且是一个普通文件,则为真。
[ -r file ] file 存在且是可读的,则为真。
[ -w file ] file存在且是可写的,则为真。
[ -x file ] file 存在且是可执行的,则为真。
[ -b file ] file 存在,且是一个块特殊文件,则为真。
[ -c file ] file 存在,且是一个字特殊文件,则为真。
[ -g file ] file 存在且已经设置了SGID,则为真。
[ -k file ] file 存在且已经设置了粘制位,则为真。
[ -p file ] file 存在且是一个名字管道(F如果O),则为真。
[ -s file ] file 存在且大小不为0,则为真。
[ -t FD ] 文件描述符 FD 打开且指向一个终端,则为真。
[ -u file ] file 存在且设置了SUID (set user ID),则为真。
[ -O file ] file 存在且属有效用户ID,则为真。
[ -G file ] file 存在且属有效用户组,则为真。
[ -L file ] file 存在且是一个符号连接,则为真。
[ -N file ] file 存在 and has been mod,如果ied since it was last read则为真。
[ -S file ] file 存在且是一个套接字,则为真。
[ file1 -ot file2 ] file1 比 file2 要老, 或者 file2 存在且 file1 不存,在则为真。
[ file1 -ef file2 ] file1 和 file2 指向相同的设备和节点号,则为真。
[ $a -gt $b -a $a -lt $c ] -a 与
[ $a -gt $b -o $a -lt $c ] -o 或
[ ! -z ${name} ] ! 取反
双中括号条件判断
[[ ]]
内置在shell中的一个命令,它比刚才说的[ ]
强大的多了。支持字符串中的模式匹配。
[ ]
不能使用&&
和||
,只能使用-a
和-o
[root@taotaoplus ~]# [ -r "aaa.txt" && -w "aaa.txt" ] && echo "aaa.txt 具有读写权限"
-bash: [: 缺少 `]'
[root@taotaoplus ~]# [[ -r "aaa.txt" && -w "aaa.txt" ]] && echo "aaa.txt 具有读写权限"
aaa.txt 具有读写权限
[root@taotaoplus ~]# [ -r "aaa.txt" -a -w "aaa.txt" ] && echo "aaa.txt 具有读写权限"
aaa.txt 具有读写权限
[root@taotaoplus ~]#
字符串比较时可以把右边的作为一个模式(这是右边的字符串不加双引号的情况下。如果右边的字符串加了双引号,则认为是一个文本字符串。),而不仅仅是一个字符串,比如[[ hello == hell? ]],结果为真。
双小括号条件判断
let条件判断
更多推荐
已为社区贡献1条内容
所有评论(0)