程序员人生 网站导航

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

栏目:php教程时间:2016-11-17 09:21:52

在shell中,内建(builtin)命令test,格式以下:

test expr [ expr ]

test命令用于测试条件表达式expr的结果,为true时返回0,为false时返回1,每一个运算符和操作数都是1个独立的参数。对条件表达式测试时使用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个参数:如果第1个参数为“!”,第2个参数非空时结果为true。如果第1个参数为1元(单目)条件运算符,则1元条件运算测试为true时结果为true。否则,若第1个参数是无效的1元条件运算符,结果为false。

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

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

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 文件存在且最后1次读文件时对文件进行了修改的为true。 -O file 文件存在且具有有功效户id时为true。 -S file 文件存在且为socket时为true。 file1 -ef file2 file1和file2指向同1个装备和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时为truestring 字符串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
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐