注意:在 “[” 之后和 “]” 之前空格是必须的。
通常代码形式如下:
if [ -n "$varname" ]; then echo "hello" else echo '$varname' is null! fi在条件表达式里始终用双引号将变量引起,有以下两个原因:
- 将变量解释为一个单词。
- 如果变量是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) |
文件测试
下表列出常用的文件测试表达式。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 |
No comments:
Post a Comment