1. 判断式
test命令用于检测文件类型和比较值。
判断文件是否存在:
[work@www sh]$ test -e file.txt && echo "exist" || echo "not exist"
not exist
[work@www sh]$
检查文件类型:
-e 文件是否存在 test -e filename
-f 文件是否存在,且为文件 file
-d 文件是否存在,且为目录 directory
-b 文件是否存在,且为block device设备
-c 文件是否存在,且为character device设备
-S 文件是否存在,且为Socket文件
-p 文件是否存在,且为FIFO(pipe)文件
-L 文件是否存在,且为连接文件
-f 文件是否存在,且为文件 file
-d 文件是否存在,且为目录 directory
-b 文件是否存在,且为block device设备
-c 文件是否存在,且为character device设备
-S 文件是否存在,且为Socket文件
-p 文件是否存在,且为FIFO(pipe)文件
-L 文件是否存在,且为连接文件
检查文件权限
-r 文件是否存在,且可读权限
-w 文件是否存在,且可写权限
-x 文件是否存在,且可执行权限
-u 文件是否存在,且具有SUID属性
-g 文件是否存在,且具有SGID属性
-k 文件是否存在,且具有 Sticky bit 属性
-s 文件是否存在,且为 非空白文件
-w 文件是否存在,且可写权限
-x 文件是否存在,且可执行权限
-u 文件是否存在,且具有SUID属性
-g 文件是否存在,且具有SGID属性
-k 文件是否存在,且具有 Sticky bit 属性
-s 文件是否存在,且为 非空白文件
两个文件比较
-nt newer than 判断file1是否比file2新
test file1 -nt file2
-ot older than 判断file1是否比file2旧
-ef 判断是否为同一文件,可用在判断hard link上,判定两个文件是否指向同一个inode
test file1 -nt file2
-ot older than 判断file1是否比file2旧
-ef 判断是否为同一文件,可用在判断hard link上,判定两个文件是否指向同一个inode
两个整数的判断
-eq equal 相等, test n1 -eq n2
-ne not equal 不相等
-gt greater than 大于
-lt less than 小于
-ge greater than or equal 大于等于
-le less than or equal 小于等于
-ne not equal 不相等
-gt greater than 大于
-lt less than 小于
-ge greater than or equal 大于等于
-le less than or equal 小于等于
判定字符串
test -z string 判断字符串是否为0, string为空,返回true, test -z string
test -n string 判断字符串是否非为0, string 为空, 返回false, -n可省略
test str1 = str2 是否相等
test str1 != str2 是否不相等
test -n string 判断字符串是否非为0, string 为空, 返回false, -n可省略
test str1 = str2 是否相等
test str1 != str2 是否不相等
多重条件
-a 同时成立,and , test -r file -a -x file : file同时具有rx权限时,返回true
-o 任意一个成立, or
! 取反
-o 任意一个成立, or
! 取反
如下:
#!/bin/bash
test -e pass && echo "file exist"
test -f pass && echo "regular file"
test -d pass && echo "directory"
2. 判断符号[]
判断符号[] 的使用同test基本一样。
[]里面每个组件都需要用空格分隔。
变量最好用引号包围。
#!/bin/bash
name="Bill gates"
[ "$name" == "bill gates" ]
echo $?
地址: http://blog.csdn.net/yonggang7/article/details/40479141