条件测试
1.shell的测试命令
test命令的语法格式为: test 表达式
或者:[ 表达式 ] 在表达式的前后都有空格
2.测试文件属性
表达式 | 说明 |
-b file | 文件存在且为块设备,真 |
-c file | 文件存在且为字符设备 |
-r file | 文件存在且为只读 |
-w file | 文件存在且为可写入 |
-x file | 文件存在且为可执行 |
-s file | 文件存在且长度大于0 |
-d file | file是一个目录 |
-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 n2 | n1等于n2 |
n1 -ne n2 | n1不等于n2 |
n1 -gt n2 | n1大于n2 |
n1 -lt n2 | n1小于n2 |
n1 -ge n2 | n1大于等于n2 |
n1 -le n2 | n1小于等于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 s1 | s1的长度为0,真 |
-n s1 | s1的长度不为0 |
s1=s2 | s1与s2相等 |
s1!=s2 | s1与s2不等 |
s1 | s1不是空串 |
相等测试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