条件测试

条件测试

1.shell的测试命令

test命令的语法格式为:  test 表达式

或者:[ 表达式 ]  在表达式的前后都有空格

2.测试文件属性

文件属性测试表达式
表达式说明
-b file文件存在且为块设备,真
-c file文件存在且为字符设备
-r file文件存在且为只读
-w file文件存在且为可写入
-x file文件存在且为可执行
-s file文件存在且长度大于0
-d filefile是一个目录
-f file文件是一个普通文件
-e file文件存在









测试文件存在的filee:

chen@chen-IdeaPad-Y430:~/test$ cat filee 
#!/bin/bash
#filename:filee
echo "Please enter the filename:"
read FILENAME
if test -e $FILENAME ; then
ls -l $FILENAME
else
touch $FILENAME
fi

3.测试数值

数值测试表达式
选项说明
n1 -eq n2n1等于n2
n1 -ne n2n1不等于n2
n1 -gt n2n1大于n2
n1 -lt n2n1小于n2
n1 -ge n2n1大于等于n2
n1 -le n2n1小于等于n2






小于等于测试numberle:

chen@chen-IdeaPad-Y430:~/test$ cat numberle 
#!/bin/bash
#filename:numberle
echo "please enter the first number:"
read N1
echo "please enter the second number:"
read N2
if test $N1 -le $N2 ;then
echo "$N1 less and equal than $N2"
else
echo "$N1 not less and equal than $N2"
fi

4.测试字符串

字符串测试表达式
选项说明
-z s1s1的长度为0,真
-n s1s1的长度不为0
s1=s2s1与s2相等
s1!=s2s1与s2不等
s1s1不是空串






相等测试stringequal:

chen@chen-IdeaPad-Y430:~/test$ cat stringequal 
#!/bin/bash
#filename:stringequal
echo "please enter the first string:"
read S1
echo "please enter the second string:"
read S2
if test $S1 = $S2 ;then
echo "equal"
else
echo "not equal"
fi

5.测试逻辑运算符

逻辑运算符
逻辑操作符说明
-a二进制“与”
-o二进制“或”
一元“非”




逻辑与测试myand2:

chen@chen-IdeaPad-Y430:~/test$ cat myand2
#!/bin/bash
#filename:myand2
echo "please enter filename:"
read FILE
if test -r $FILE -a -f $FILE ;then
echo "normal and readonly"
else
echo "not normal and readonly"
fi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值