文件类型测试
-e条件运算符用来测试一个文件是否存在(包括所有文件类型,目录等)
- if [[ -e $filename ]]; then
- echo "$filename exists"
- fi
也可以测试指定类型的文件
- if [[ -f $filename ]]; then
- echo "$filename is a regular file"
- elif [[ -d $filename ]]; then
- echo "$filename is a directory"
- elif [[ -p $filename ]]; then
- echo "$filename is a named pipe"
- elif [[ -S $filename ]]; then
- echo "$filename is a named socket"
- elif [[ -b $filename ]]; then
- echo "$filename is a block device"
- elif [[ -c $filename ]]; then
- echo "$filename is a character device"
- fi
- if [[ -L $filename ]]; then
- echo "$filename is a symbolic link (to any file type)"
- fi
对于软链接,使用-L测试时,当链接指向的目标文件不存在时会返回false
- if [[ -L $filename || -e $filename ]]; then
- echo "$filename exists (but may be a broken symbolic link)"
- fi
-
- if [[ -L $filename && ! -e $filename ]]; then
- echo "$filename is a broken symbolic link"
- fi
字符串比较和匹配
在两个带引号的字符串之间比较时使用==操作符。!=操作符则是否则的比较
- if [[ "$string1" == "$string2" ]]; then
- echo "\$string1 and \$string2 are identical"
- fi
- if [[ "$string1" == "$string2" ]]; then
- echo "\$string1 and \$string2 are identical"
- fi
如果右则没有引号,那么它是以通配符的模式作比较。
- string1='abc'
- pattern='a*'
- if [[ "$string1" == $pattern ]]; then
- # the test is true
- echo "The string $string1 matches the pattern $pattern"
- fi
- if [[ "$string1" != "$pattern" ]]; then
- echo "The string $string1 is not equal to the string $pattern"
- fi
操作符以字典顺序来比较字符串(它们没有小或等于或大于的说法)
可以测试空字符串
- if [[ -n $string ]]; then
- echo "$string is non-empty"
- fi
- if [[ -z "${string// }" ]]; then
- echo "$string is empty or contains only spaces"
- fi
- if [[ -z $string ]]; then
- echo "$string is empty"
- fi
以上的-z检查可能表示$string没有被设置或者已经设置了但为空字符。为了区分空字符和未设置,使用:
- if [[ -n ${string+x} ]]; then
- echo "$string is set, possibly to the empty string"
- fi
- if [[ -n ${string-x} ]]; then
- echo "$string is either unset or set to a non-empty string"
- fi
- if [[ -z ${string+x} ]]; then
- echo "$string is unset"
- fi
- if [[ -z ${string-x} ]]; then
- echo "$string is set to an empty string"
- fi
其中x是任意的,以表格形式如下:
- +-------+-------+-----------+
- $string is: | unset | empty | non-empty |
- +-----------------------+-------+-------+-----------+
- | [[ -z ${string} ]] | true | true | false |
- | [[ -z ${string+x} ]] | true | false | false |
- | [[ -z ${string-x} ]] | false | true | false |
- | [[ -n ${string} ]] | false | false | true |
- | [[ -n ${string+x} ]] | false | true | true |
- | [[ -n ${string-x} ]] | true | false | true |
- +-----------------------+-------+-------+-----------+
文件权限测试
- if [[ -r $filename ]]; then
- echo "$filename is a readable file"
- fi
- if [[ -w $filename ]]; then
- echo "$filename is a writable file"
- fi
- if [[ -x $filename ]]; then
- echo "$filename is an executable file"
- fi