条件判断式
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.按照文件类型进行判断
玩Linux的运维童鞋都应该知道“Linux一切皆文件”,我们大致将这些文件件分为七类:
a>.块设备文件;
b>.字符设备文件;
c>.目录文件;
d>.普通文件;
e>.链接文件;
f>.管道文件;
g>.套接字文件;
1.两种判断格式
1 [root@yinzhengjie ~]# test -e /etc/fstab 2 [root@yinzhengjie ~]# echo $?3 04 [root@yinzhengjie ~]# [ -e /etc/fstab ]5 [root@yinzhengjie ~]# echo $?6 07 [root@yinzhengjie ~]
2.案例展示
1 [root@yinzhengjie ~]# test -d /root/ && echo "yes" || echo "no"2 yes3 [root@yinzhengjie ~]# [ -d /root/ ] && echo "yes" || echo "no"4 yes5 [root@yinzhengjie ~]#
二.按照文件权限进行判断
案例展示:
1 [root@yinzhengjie ~]# test -w yinzhengjie.txt && echo "yes" || echo "no"2 yes3 [root@yinzhengjie ~]# 4 [root@yinzhengjie ~]# [ -w /root/yinzhengjie.txt ] && echo yes || echo no5 yes6 [root@yinzhengjie ~]#
三.两个文件之间进行比较
案例展示:
1 [root@yinzhengjie ~]# ln /root/yinzhengjie.txt /tmp/test.txt2 [root@yinzhengjie ~]# ll -i /root/yinzhengjie.txt 3 651800 -rw-r--r-- 2 root root 26 Oct 11 03:39 /root/yinzhengjie.txt4 [root@yinzhengjie ~]# 5 [root@yinzhengjie ~]# ll -i /tmp/test.txt 6 651800 -rw-r--r-- 2 root root 26 Oct 11 03:39 /tmp/test.txt 7 [root@yinzhengjie ~]# 8 [root@yinzhengjie ~]# [ /root/yinzhengjie.txt -ef /tmp/test.txt ] && echo "是硬链接" || echo "不是同一个文件"是硬链接 9 [root@yinzhengjie ~]#
四.两个整数之间比较
案例展示:
1 [root@yinzhengjie ~]# [ 100 -gt 20 ] && echo "大于" || echo "no"2 大于3 [root@yinzhengjie ~]# 4 [root@yinzhengjie ~]# [ 100 -ge 100 ] && echo "大于等于" || echo "no"5 大于等于6 [root@yinzhengjie ~]# 7 [root@yinzhengjie ~]# [ 100 -lt 200 ] && echo "小于" || echo "no"8 小于9 [root@yinzhengjie ~]#
五.字符串的判断
案例展示:
1 [root@yinzhengjie ~]# a=yinzhengjie2 [root@yinzhengjie ~]# b=yinzhengjie3 [root@yinzhengjie ~]# [ "$a" == "$b" ] && echo yes || echo no4 yes5 [root@yinzhengjie ~]# [ "$a" == yinzhengjie ] && echo yes || echo no6 yes 7 [root@yinzhengjie ~]# [ "$a" == hello ] && echo yes || echo no 8 no 9 [root@yinzhengjie ~]#
六.多重条件判断
案例展示:
1 [root@yinzhengjie ~]# a=1002 [root@yinzhengjie ~]# [ -n "$a" -a "$a" -gt 50 ]&& echo yes || echo no3 yes4 [root@yinzhengjie ~]# a=105 [root@yinzhengjie ~]# [ -n "$a" -a "$a" -gt 50 ]&& echo yes || echo no6 no7 [root@yinzhengjie ~]#