您的位置:首页 > 运维架构 > Shell

【Bash百宝箱】shell内建命令之test

2016-09-21 20:00 519 查看
在shell中,内建(builtin)命令test,格式如下:

test expr
[ expr ]


test命令用于测试条件表达式expr的结果,为true时返回0,为false时返回1,每个运算符和操作数都是一个独立的参数。对条件表达式测试时使用一对方括号也是可以的,效果等同于test命令。

test命令支持以下4种运算符(运算符优先级从高到低):

! expr    如果expr为false,返回true。
( expr )    返回expr的值,可用以改变运算符的优先级。
expr1 -a expr2    如果expr1和expr2都为true时,返回true。
expr1 -o expr2    如果expr1或expr2为true时,返回true。


test命令对条件表达式求值时,取决于其参数格式,规则如下。

没有任何参数:结果为false。

1个参数:参数非空时结果为true。

2个参数:如果第一个参数为“!”,第二个参数非空时结果为true。如果第一个参数为一元(单目)条件运算符,则一元条件运算测试为true时结果为true。否则,若第一个参数是无效的一元条件运算符,结果为false。

3个参数:如果第二个参数为二元(双目)条件运算符,则结果就是第一个参数和第三个参数作二元条件运算的结果。有3个参数时,“-a”和“-o”作为二元条件运算符。如果第一个参数为“!”,则结果与第二个参数和第三个参数作为表达式的测试结果相反。如果第一个参数为左圆括号“(”,第三个参数为右圆括号“)”,则结果就是第二个参数的测试结果。

4个参数:如果第一个参数为“!”,则测试结果与后面三个参数构成的表达式的测试结果相反,否则按照运算符的优先级和上面列出的规则处理。

5个及5个以上的参数:按照运算符的优先级和上面列出的规则处理。

条件表达式可以对文件、字符串、数字进行测试,下面分别列出这些用法。

test命令对文件进行处理:

-a file
文件存在时为true。
-b file
文件存在且为特殊的块block文件时为true。
-c file
文件存在且为特殊的字符character文件时为true。
-d file
文件存在且为目录(文件夹)时为true。
-e file
文件存在时为true。
-f file
文件存在且为普通文件时为true。
-g file
True if file exists and is set-group-id.
-h file
文件存在且为符号(软链接)文件时为true。
-k file
文件存在且设置了sticky位时为true。
-p file
文件存在且为有名管道FIFO时为true。
-r file
文件存在且可读时为true。
-s file
文件存在且长度大于零时为true。
-t fd
文件描述符已打开且指向终端时为true。
-u file
True if file exists and its set-user-id bit is set.
-w file
文件存在且可写时为true。
-x file
文件存在且可执行时为true。
-G file
文件存在且拥有有效组id时为true。
-L file
文件存在且为符号(软链接)文件时为true。
-N file
文件存在且最后一次读文件时对文件进行了修改的为true。
-O file
文件存在且拥有有效用户id时为true。
-S file
文件存在且为socket时为true。
file1 -ef file2
file1和file2指向同一个设备和inode时为ture。
file1 -nt file2
file1比file2新或者file1存在而file2不存在时为true。
file1 -ot file2
file2比file1新或者file2存在而file1不存在时为true。


test命令对字符串进行处理:

-o optname
通过shell内建命令set的选项“-o”激活了optname时为true。
-v varname
设置了shell变量varname时为true。
-R varname
设置了shell变量varname且为引用变量时为true。
-z string
字符串string长度为0时为true。
string
字符串string长度非0时为true。
-n string
字符串string长度非0时为true。
string1 == string2
字符串string1和string2相同时为true。
string1 = string2
字符串string1和string2相同时为true。用于test命令,符合POSIX兼容性。
string1 != string2
字符串string1和string2不同时为true。
string1 < string2
按字典序,字符串string1比string2靠前时为true。
string1 > string2
按字典序,字符串string1比string2靠后时为true。


test命令对数字进行处理:

arg1 -eq arg2    arg1是否等于arg2
arg1 -ne arg2    arg1是否不等于arg2
arg1 -lt arg2    arg1是否小于arg2
arg1 -le arg2    arg1是否小于或等于arg2
arg1 -gt arg2    arg1是否大于arg2
arg1 -ge arg2    arg1是否大于或等于arg2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: