Wednesday, August 14, 2013

bash笔记(三)——条件测试

if 语句之后除了可以跟命令行之外,还可以用[...]结构,[...]结构和内部命令 test 是等效的,即 [ string1 = string2 ]test string1 = string2 的结果是相同的。另外在bash 2.05之后的版本还可以用[[...]] 结构,[[...]] 和[...]之间的不同可参考: http://stackoverflow.com/a/3427931/1036923 .

注意:在 “[” 之后和 “]” 之前空格是必须的。

通常代码形式如下:
if [ -n "$varname" ]; then
    echo "hello"
else
    echo '$varname' is null!
fi
在条件表达式里始终用双引号将变量引起,有以下两个原因:

  1. 将变量解释为一个单词。
  2. 如果变量是null, 没有双引号则上例中条件测试将变为[ -n ] ,它总是返回true; 用了双引号则表达式为[ -n "" ] ;

条件组合

if command && [ condition ] && [ condition ] || [ condition ]; then


if command && [ \( condition \) -a \( condition \) -o \( condition \) ]; then
...


-a 和 -o 只能用在测试条件表达式中

字符串比较

Operator True if...
str1 = str2 str1 matches str2
str1 != str2 str1 does not match str2
str1 < str2 str1 is less than str2
str1 > str2 str1 is greater than str2
-n str1 str1 is not null (has length greater than 0)
-z str1 str1 is null (has length 0)
注:bash 没有 >= 和 <= 比较符。

文件测试

下表列出常用的文件测试表达式。

Operator True if...
-a file file exists
-d file file exists and is a directory
-e file file exists; same as -a
-f file file exists and is a regular file(i.e., not a directory or other special type of file)
-r file You have read permission on file
-s file file exists and is not empty
-w file You have write permission on file
-x file You have execute permission on file, or directory search permission if it is a directroy
-N file file was modified since it was last read
-O file You own file
-G file file's group ID matchs yours (or one of yours, if you are in multiple groups)
file1 -nt file2 file1 is newer than file2
file1 -ot file2 file1 is older than file2


算术比较


Test Comparison
-lt Less than
-le Less than or equal
-eq Equal
-ge Greater than or equal
-gt Greater than
-ne Not equal
注:bash还有针对整数比较的独立语法,效率更高,所以要优先用它而不是上表列出的算术比较运算符。

No comments:

Search This Blog