shell学习之条件测试

test命令用于测试文件状态、数字和字符串,expr命令测试和执行数值输出。

退出状态可用$?查看,0表示正确,其他数字表示错误。

test

一、测试文件状态

test命令有两种格式:

1 test <condition>
2 [ <condition> ]

注意:[]两端都要有空格。常用于测试文件状态的选项如下:

1 -d 目录
2 -s 文件长度大于0、非空
3 -f 正规文件
4 -w 可写
5 -L 符号连接
6 -u 文件有suid设置
7 -r 可读
8 -x 可执行

例子如下:

 1 lee@ubuntu:~/shell_study/cu$ ls -al
 2 总用量 16
 3 drwxr-xr-x  2 lee lee 4096 2012-03-05 23:19 .
 4 drwxr-xr-x 16 lee lee 4096 2012-05-26 13:43 ..
 5 -rw-r--r--  1 lee lee   41 2012-03-05 23:19 file1
 6 -rw-r--r--  1 lee lee   47 2012-03-05 23:19 file2
 7 lee@ubuntu:~/shell_study/cu$ [ -x file1 ]
 8 lee@ubuntu:~/shell_study/cu$ echo $?
 9 1
10 lee@ubuntu:~/shell_study/cu$ [ -r file1 ]
11 lee@ubuntu:~/shell_study/cu$ echo $?
12 0

在测试时可以用逻辑操作符:

1 -a 逻辑与
2 -o 逻辑或
3 ! 逻辑否

二、字符串测试

字符串测试有5种格式:

1 test "<string>"
2 test <string_operator> "<string>"
3 test "<string>" <string_operator>  "<string>"
4 [ <string_operator> <string> ]
5 [ <string> <string_operator> <string> ]

其中string_operator可以为下列之一,需要注意的是操作符两边都要有空格:

== 两个字符串相等 ,与 = 等价
!= 两个字符串不等
-z 空串
-n 非空串

例子如下:

1 lee@ubuntu:~/shell_study/cu$ str="hello world"
2 lee@ubuntu:~/shell_study/cu$ echo $str
3 hello world
4 lee@ubuntu:~/shell_study/cu$ [ $str == "hello world" ]
5 bash: [: 过多的参数
6 lee@ubuntu:~/shell_study/cu$ [ "$str" == "hello world" ]
7 lee@ubuntu:~/shell_study/cu$ echo $?
8 0

需要注意的是,当字符串有空格时,要用双引号,使用双引号可引用除字符$、`、\外的任意字符或字符串。这些特殊字符分别为美元符号,反引号和反斜线,对s h e l l来说,它们有特殊意义。

在test的时候,如果变量str为空或者带有空格,则会出现第五行的错误,解决方案还是双引号,参考http://mywiki.wooledge.org/BashPitfalls

另外,==的功能在[[]]和[]中的行为是不同的,如下:

1 [[ $a == z* ]]    # 如果$a以"z"开头(模式匹配)那么将为true
2 [[ $a == "z*" ]] # 如果$a等于z*(字符匹配),那么结果为true
3 [ $a == z* ]      # File globbing 和word splitting将会发生
4 [ "$a" == "z*" ] # 如果$a等于z*(字符匹配),那么结果为true

三、数值测试

格式如下:

1 [ "<number>" number_operator "<number>" ]

number_operator为:

1 -eq 数值相等。
2 -ne 数值不相等。
3 -gt 第一个数大于第二个数。
4 -lt 第一个数小于第二个数。
5 -le 第一个数小于等于第二个数。
6 -ge 第一个数大于等于第二个数。

 

expr

expr命令一般用于整数值,但是也可以用于字符串,格式为:

1 expr <argument> <operator> <argument>

例子:

 1 lee@ubuntu:~/shell_study/cu$ expr 10 + 10
 2 20
 3 lee@ubuntu:~/shell_study/cu$ expr 10 - 10
 4 0
 5 lee@ubuntu:~/shell_study/cu$ expr 10 * 10
 6 expr: 语法错误
 7 lee@ubuntu:~/shell_study/cu$ expr 10 / 10
 8 1
 9 lee@ubuntu:~/shell_study/cu$ expr 10 \* 10
10 100

需要注意的是,为了避免shell的替代,乘法时要用反斜杠转义。

一、增量计数

expr可以用于在循环中的计数,如下例:

1 lee@ubuntu:~/shell_study/cu$ loop=1
2 lee@ubuntu:~/shell_study/cu$ loop=`expr $loop + 1`
3 lee@ubuntu:~/shell_study/cu$ echo $loop
4 2

需要注意的是,expr的退出状态和shell的退出状态刚好相反,即expr中1表示正确退出,如:

1 lee@ubuntu:~/shell_study/cu$ value=hello
2 lee@ubuntu:~/shell_study/cu$ expr $value = "hello"
3 1
4 lee@ubuntu:~/shell_study/cu$ echo $?
5 0

二、模式匹配

格式:

1 expr <string> : <regular>

比如:

1 lee@ubuntu:~$ value=hello
2 lee@ubuntu:~$ expr $value : '.*'
3 5
posted @ 2012-05-26 14:25  leealways87  阅读(200)  评论(0)    收藏  举报