shell中if语句–test
test命令
test是shell内置命令,用来检测某个条件是否成立
test通常和if语句一起使用,并且大部分if语句都依赖test
shell test命令的用法有两种:
第一种:
test expression
第二种:
[ expression ]
注意:
1.当test判断expression成立时,退出状态为0,否则为非0值
2.[ ]和expression的两边都有空格,这个空格是必须的,否则会导致语法错误
3.[ ]写法更简介,使用频率更高
test命令可以判断三类条件:
数值比较
字符串比较
文件比较
shell中if语句–test之数值比较
est命令的数值比较功能:
#!/bin/bash
#数值条件测试可以用在数字和变量上
val1=10
val2=20
if [ $val1 -gt 5 ] #检查变量val1是否大于5
then
echo "$val1 is greater than 5" #大于5时执行此行代码
fi
if [ $val1 -eq $val2 ] #检查两个变量是否相等
then
echo "The values are equal"
else
echo "The values are different"
fi
#!/bin/bash
val1=`echo "scale=4;10 / 3 " | bc`
echo "The test value is $val1"
#不能在test命令中使用浮点值
if [ $val1 -gt 3 ]
then
echo "The result is larger than 3"
fi
注意:不能在test命令中使用浮点值
shell中if语句—test之字符串比较
比较字符串是否相等
[ str1 = str2 ]
[ str1 != str2 ]
#!/bin/bash
#比较字符串是否相等
testing=root
if [ $USER = $testing ]
then
echo "Welcome $testing"
else
echo "This is not $testing"
fi
注意:test比较字符串相等性时会将所有的标点和大写也考虑在内
比较字符串的大小
[ str1 < str2 ]
[ str1 > str2 ]
注意:这里比较的是字符串,而不是字符串的长度
字符串大小的比较遵循字典顺序,规则如下:
1.如果第一个字符串是第二个字符串的前缀,那么第一个小(比如a小于about)
2.从字符串的开头比较,按照字母顺序,a比b小(比如about小于ball)
3.如果第一个字符相同,再比较第二个(比如about小于above)
#!/bin/bash
val1=aboot
val2=above
#大于小于符号必须转义
#否则shell会把它们当作重定向
if [ $val1 \> $val2 ]
then
echo "$val1 is greater than $val2"
else
echo "$val1 is less than $val2"
fi
比较字符串的长度
[ -n str1 ] #检查str1的长度是否非0
[ -z str1 ] #检查str1的长度是否为0
#!/bin/bash
val1=testing
val2=''
if [ -n "$val1" ]
then
echo "The string '$val1' is not empty"
else
echo "The string '$val1' is empty"
fi
if [ -z "$val2" ]
then
echo "The string '$val2' is empty"
else
echo "The string '$val2' is not empty"
fi
if [ -z "$val3" ]
then
echo "The string '$val3' is empty"
else
echo "The string '$val3' is not empty"
fi
shell中if语句—test之文件比较
检查file是否存在并是一个目录
#!/bin/bash
#检查file是否存在并是一个目录
if [ -d $HOME ]
then
echo "Your HOME directroy exists"
cd $HOME
ls -a
else
echo "There is a problem with your HOME directory"
fi
-r检查文件是否存在并可读
#!/bin/bash
# -r检查文件是否存在并可读
pwdfile=/etc/shadow
if [ -f $pwdfile ] #先检查$pwdfile是否存在并是一个文件
then
if [ -r $pwdfile ] #满足上面条件再检查它是否可读
then
tail $pwdfile
else
echo "Sorry,Permission denied.unable to read"
fi
else
echo "Sorry.the file $pwdfile does not exist"
fi
-s检查文件是否存在并为非空
#!/bin/bash
# -s检查文件是否存在并为非空
file=test
touch $file
if [ -s $file ]
then
echo "The file $file exists and has data in it"
else
echo "The $file exists and is empty"
fi
使文件不为空,进行检测