接触shell脚本后,发现test命令在脚本中的应用非常多。学习shell脚本test命令是必须要掌握的,而且他很容易被掌握。
test命令可以处理shell脚本的各类工作。它产生的不是一般的输出(文本内容等),而是可使用的退出状态(true和false)。test接受各种不同的参数,可控制它要执行哪一种测试。
test命令有两种模式:
第一种:可以通过man test查看:test [-OPTION] EXPRESSION
不带参数:
点击(此处)折叠或打开
- if test "$str1 = $str2"
- then
- ......
- fi
点击(此处)折叠或打开
- if test -x "$file"
- then
- ......
- fi
第二种:[‘空’[-OPTION] EXPRESSION‘空 ’ ] 注意左右方括号和测试表达式之间 必须 存在一个空格.
不带参数:
点击(此处)折叠或打开
- if [ "$str1 = $str2" ]
- then
- ......
- fi
点击(此处)折叠或打开
- if [ -z "$str1" -a -z "$str2" ]
- then
- ......
- fi
( EXPRESSION )
EXPRESSION is true
! EXPRESSION
EXPRESSION is false
表达式组合:
EXPRESSION1 -a EXPRESSION2
both EXPRESSION1 and EXPRESSION2 are true
EXPRESSION1 -o EXPRESSION2
either EXPRESSION1 or EXPRESSION2 is true
[-OPTION]参数如下(栽man test):
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
FILE1 -ef FILE2
FILE1 and FILE2 have the same device and inode numbers
FILE1 -nt FILE2
FILE1 is newer (modification date) than FILE2
FILE1 -ot FILE2
FILE1 is older than FILE2
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-g FILE
FILE exists and is set-group-ID
-G FILE
FILE exists and is owned by the effective group ID
-h FILE
FILE exists and is a symbolic link (same as -L)
-k FILE
FILE exists and has its sticky bit set
-L FILE
FILE exists and is a symbolic link (same as -h)
FILE exists and is owned by the effective user ID
-p FILE
FILE exists and is a named pipe
-r FILE
FILE exists and read permission is granted
-s FILE
FILE exists and has a size greater than zero
-S FILE
FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE
FILE exists and its set-user-ID bit is set
-w FILE
FILE exists and write permission is granted
-x FILE
FILE exists and execute (or search) permission is granted
FROM: http://blog.chinaunix.net/uid-28728968-id-4407312.html