您的位置:首页 > 运维架构 > Shell

shell中的条件判断

2016-06-29 00:29 375 查看
利用test命令来实现条件判断,而不是利用command的返回值

1.有两种模式:

test命令

if test condition
then
commands
fi


中括号[]代替test

if [condition]
then
commands
fi


其中的condition也可以是复合的条件判断

#与
[condition1]&&[condition2]
#或
[condition1]||[condition2]


test 支持三类条件:

#1.**数值比较**

#test 整数1 –eq 整数2                    整数相等
#test 整数 1 –ge 整数2                   整数1大于等于整数2
#test 整数1 –gt 整数 2                   整数1大于整数2
#test 整数1 –le 整数 2                   整数1小于等于整数2
#test 整数1 –lt 整数 2                   整数1小于整数2
#test 整数1 –ne 整数 2                   整数1不等于整数2

if [ 1 -eq 2 ]
then
echo "1 is equal to 2"
else
echo "1 is not equal to 2"
fi
#2.字符串比较
#test –n 字符串                       字符串的长度非零
#test –z 字符串                       字符串的长度为零
#test 字符串1 = 字符串 2              字符串相等
#test 字符串1 !=字符串2               字符串不等
#注意< >要用转义符号
if [ $str1 \> $str2]
then
echo "$str1 > $str2"
else
echo "$str1 <= $str2"
fi
#if 后面还可以进行这样的比较
#判断str长度是否为非0
if [ -n "$str" ]
#判断str长度是否为为0
if [ -z "$str" ]
#有点小懒,就不举例了,嘿嘿

#3.文件比较
#test  File1 –ef  File2  两个文件具有同样的设备号和i结点号
#test  File1 –nt  File2  文件1比文件2 新
#test  File1 –ot  File2  文件1比文件2 旧
#test –b File            文件存在并且是块设备文件
#test –c File            文件存在并且是字符设备文件
#test –d File            文件存在并且是目录
#test –e File            文件存在
#test –f File            文件存在并且是正规文件
#test –g File            文件存在并且是设置了组ID
#test –G File            文件存在并且属于有效组ID
#test –h File            文件存在并且是一个符号链接(同-L)
#test –k File             文件存在并且设置了sticky位
#test –b File            文件存在并且是块设备文件
#test –L File            文件存在并且是一个符号链接(同-h)
#test –o File            文件存在并且属于有效用户ID
#test –p File            文件存在并且是一个命名管道
#test –r File            文件存在并且可读
#test –s File            文件存在并且是一个套接字
#test –t FD               文件描述符是在一个终端打开的
#test –u File           文件存在并且设置了它的set-user-id位
#test –w File            文件存在并且可写
#test –x File            文件存在并且可执行
if [ -d / ]
then
echo " / is a directory "
else
echo " / is not a directory "
fi


ps:关于文件的各种操作有很多,就不一一列举了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell test 条件判断