Q: “glob expansion”和”pattern matching”什么区别??
A: Glob is “Unix style pathname pattern expansion”.
test [[ ]] [] 总结表格如下:
整数比较
大于 | 小于 | 等于 | 不等于 |
if [ "$a" -gt "$b" ] | if [ "$a" -gt "$b" ] | if [ "$a" -eq "$b" ] | if [ "$a" -ne "$b" ] |
if [[ "$a" -gt "$b" ]] | if [[ "$a" -gt "$b" ]] | if [[ "$a" -eq "$b" ]] | if [[ "$a" -ne "$b" ]] |
if ((“$a” > “$b”)) | if ((“$a” < “$b”)) | if ((“$a” == “$b”)) | if ((“$a” != “$b”)) |
字符串比较
大于 | 小于 | 等于 | 不等于 |
if [ "$a" \> "$b" ] | if [ "$a" \< "$b" ] | if [ "$a" = "$b" ] if [ "$a" == "$b" ] | if [ "$a" != "$b" ] |
if [[ "$a" > "$b" ]] | if [[ "$a" < "$b" ]] | if [[ "$a" = "$b" ]] if [[ "$a" == "$b" ]] | if [[ "$a" != "$b" ]] |
[[]]与[]的比较表格
功能 | [[ ]] | [ ] | 例子 |
字符串比较 | > | \> | - |
=(or ==) | = | - | |
!= | != | - | |
表达式组合 | && | -a | [[ -n $var && -f $var ]] && echo “$var is a file” |
|| | -o | - | |
模式匹配 (Pattern matching) | =(or ==) | 木有 | [[ $name = "a*" ]] -> the string “a*” |
正则匹配(RegularExpression matching) | =~ | 木有 | [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo “It’s Friday the 13th!” |
很多情况下(视实现而定)[[]]有的而[]没有的特性
特性 |
| 例子 |
文件或文件夹存在 | -e | [[ -e $config ]] && echo ”config file exists: $config” |
文件新旧比较 | -nt/-ot | [[ $file0 -nt $file1 ]] && echo ”$file0 is newer than $file1″ |
同一个文件 | -ef | [[ $input -ef $output ]] \ && { echo ”will not overwrite input file: $input”; exit 1; } |
否定 | ! | - |
还有一些很细微的区别:
1.在[[ ]]中不处理含空格的字符串(No WordSplitting)和通配符字符串匹配(glob expansion)。因此很多参数不需要用双引号包含(need not be quoted).
file=”file name”
[[ -f $file ]] && echo “$file is a file”
file=”file name”
[ -f "$file" ] && echo “$file is a file”
2.括号()在[[ ]]中不需要用\转义(need not to be escaped).
[[ -f $file1 && ( -d $dir1 || -d $dir2) ]]
[ -f "$file1" -a \( -d "$dir1" -o -d "$dir2" \) ]
逻辑组合判断的一些例子:
if [ $condition1 ] && [ $condition2 ]
if [ $condition1 -a $condition2 ]
if [[ $condition1 && $condition2 ]]
if [ $condition1 ] || [ $condition2 ]
if [ $condition1 -o $condition2 ]
if [[ $condition1 || $condition2 ]] # Also works.
#The &&, ||, operators work within a [[ ]] test, despite giving an error within a [ ] construct.
mainly from:
http://mywiki.wooledge.org/BashFAQ/031
http://tldp.org/LDP/abs/html/comparison-ops.html