测试一般用在条件判断结构:
if
[something_to_test]then do_something
else do_something_else
fi
其中something_to_test就是测试语句
。在shell中一般有一下几种命令:
- test:
- [.. ]
- [[.. ]]
1和2是相同的,3是前两者的增强版。[[..]]可以避免很多[..]中的逻辑错误,尤其是
&&,
||,
<, and
>的时候尽量使用[[..]],但是这些情况都很少碰到,因此大多数情况下这3者的效果是一样的。
test常用选项:
字符串比较: -n STRING the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING the length of STRING is zero
STRING1 = STRING2 the strings are equal
STRING1 != STRING2 the strings are not equal
整数比较: INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2
INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2
INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2
还可以用来测试file的类型,举一个例子,其余参考man test: -d file 测试file是否存在且是一个目录
|
例子:
1 #!/bin/bash
2
3 if test -n "$1"
4 then
5 echo "the first commond_line argument is $1"
6 else
7 echo "no commond_line argument"
8 fi
9
10 if [ -z "$1" ]
11 then
12 echo "no commond_line argument"
13 else
14 echo "the first commond_line argument is $1"
15 fi
16
17 file=test.sh
18 if [[ -e "$file" ]]
19 then
20 echo "file $file exist"
21 else
22 echo "file $file not exist"
23 fi
执行结果:
lzj@lzj-laptop:~/documents/abs_guide$ ./test.sh kkk the first commond_line argument is kkk the first commond_line argument is kkk file test.sh exist
|
阅读(396) | 评论(0) | 转发(0) |