shell(2) 条件判断.doc

用于 if/while 等作为判断的条件;

 

test 命令

test condition ,在条件为 true 时返回 0

if test condition; then                   if [ condition ]; then     # 注意空格, TBD 是否支持 if 0

       ...                  <==>                   ...

fi                                               fi

 

test 的条件判断,三种类型

1 )数值比较

-eq -ge -gt -le -lt -ne

 

2 )字符串比较:

=  != < >( 注意转义 ) -n( 是否非空串 ) -z( 是否空串 )

test 中大写字符小于小写,刚好与 sort 相反

 

eg: if [ "a" /> “b” ]; then

eg: if [ -n "$1" ]; then     <==> [ "$1" ]         #$1 需要引起来,否则判断失败

eg: if [string1 -a string2]; then #string1/string2 都为真

eg: if [string1 -o string2]; then #string1 string2 为真

 

3 )文件比较:

-d file      #directory, file 是否为目录

-e           ##exist, file 是否存在

-f            #file an exist file

-r            #readable

-s           #not empty

-w          #writable

-x           #executable ,且 current user 必须有执行权限

-O          #owered by current user

-G          # 文件默认用户组为 current user group

file1 -nt file2          # file1 new than file2

file1 -ot file2          # old than

以上比较在文件不存在时将返回失败,因此可以先判断文件是否存在再执行其他比较;

 

复合条件比较

类似 C [ cond1 ] && [ cond2 ] || [ cond3 ]

 

if [ 'a' /< 'b' ] && [ 'a' /< "c" ] || [ 'a' /< 'a' ];then

 

高级特性:

双圆括号表数学表达式,也可用于数学计算, if (( $A ** 2 > 90 ))

双方括号提供模式匹配功能,可使用正则表达式, if [[ $A == r* ]]

 

TBD :怎么表示逻辑非?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值