条件测试语法

语法

支持三种格式的条件测试语法

  • test<测试表达式>
  • [ <测试表达式> ]
  • [[ <测试表达式> ]]

格式1和格式2是等价的,格式3为扩展的test命令

在[[]]中可以使用通配符进行匹配。&&、||、>、<等操作符可以应用与[[]]中,但不能应用与[]中。

范例

文件存在则输出1,文件不存在则输出0

[root@chenfanlinux ~]#  [ -f /etc/passwd ] && echo 1||echo 0
1
[root@chenfanlinux ~]# test -f /etc/passwd && echo 1||echo 0
1
[root@chenfanlinux ~]#  [[ -f /etc/passwd ]] && echo 1||echo 0
1
[root@chenfanlinux ~]#  [[ -f /etc/passd ]] && echo 1||echo 0
0

非!的写法
test.txt文件如果不存在,则创建。

[root@chenfanlinux ~]# test ! -f test1.txt && touch test.txt || ehco "test1.txt已经存在"
[root@chenfanlinux ~]# test ! -f test1.txt && touch test1.txt || echo "test1.txt已经存在"
test1.txt已经存在
[root@chenfanlinux ~]# [ ! -f test.txt ] && touch test.txt || echo 'test.txt已经存在'
[root@chenfanlinux~]# [ ! -f test.txt ] && touch test.txt || echo 'test.txt已经存在'
test.txt已经存在

test 或 [] 测试语法

从功能上来看 test 测试表达式 命令等同于 [测试表达式] ,因此这里将它们归纳在一起进行总结。

数值测试

参数说明

-eq等于则为真
-ne不等于则为真
-gt大于则为真
-ge大于等于则为真
-lt小于则为真
-le小于则为真

范例

判断两个数是否相等

[root@chenfanlinux ~]# num1=1
[root@chenfanlinux ~]#chenfanlinux num2=2
[root@chenfanlinux ~]# [ $num1 -eq $num2 ] && echo "两个数相等" || echo "两个数不相等"
两个数不相等

数值运算

[root@chenfanlinux ~]# a=5
[root@chenfanlinux ~]# b=6
[root@chenfanlinux ~]# c=$[a+b]
[root@chenfanlinux ~]# echo $c
11

[root@chenfanlinux ~]# ((c=a+b))
[root@chenfanlinux ~]# echo $c
11

[root@chenfanlinux ~]# c=`expr $a + $b`
[root@chenfanlinux ~]# echo $c
11

[root@chenfanlinux ~]# let c=a+b
[root@chenfanlinux ~]# echo $c
11
  • (())
  • let
  • expr
  • bc(小数)
  • $[]

字符串测试

参数说明

“串1” = “串2”若串1等于串2则真,可以使用”==”代替”=”
“串1” != “串2”若串1不等于串2则真,但不能用”!==” 代替”!=”
-z “字符串”若串长度为0则真,-z可以理解为zero
-n “字符串”若串长度不为0则真,-n可以理解为no zero

范例

比较两个字符串是否相同

num1="chenfan"
num2="chenfanlinux"
if [ "$num1" = "$num2" ]
then
    echo '两个字符串相等!'
else
    echo '两个字符串不相等!'
fi

文件测试

参数说明

-e 文件名如果文件存在则为真
-r 文件名如果文件存在且可读则为真
-w 文件名如果文件存在且可写则为真
-x 文件名如果文件存在且可执行则为真
-s 文件名如果文件存在且至少有一个字符则为真
-d 文件名如果文件存在且为目录则为真
-f 文件名如果文件存在且为普通文件则为真
-c 文件名如果文件存在且为字符型特殊文件则为真
-b 文件名如果文件存在且为块特殊文件则为真

范例

文件存在则打印存在

cd /bin
if test -e ./bash
then
    echo '文件已存在!'
else
    echo '文件不存在!'
fi

逻辑操作符

参数说明

范例

判断文件是否同时存在

[root@chenfanlinux ~]# f1='/etc/rc.local'
[root@chenfanlinux ~]# f2='/etc/pass'

[root@chenfanlinux ~]# [ -f "$f1" -o -f "$f2" ] && echo 1|| echo 0
1
[root@chenfanlinux ~]# [ -f "$f1" -a -f "$f2" ] && echo 1|| echo 0
0

原文:大专栏  Bash编程入门之条件测试(三)


01-17 22:20
查看更多