bash test 总结


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值