linux 判断字符串格式,shell编程,if-then、else,case,数值、字符串、文件类型比较检测,[ ],(()),[[ ]]...

if-then语句:

if  command1;  then

command2

fi

如果command1命令执行返回的状态码为0,则执行command2命令。

if-then-else语句:

if  command;  then

command

else

command

fi

elif语句:

if  command ;  then

connamd

elif  command ;  then

command

else

command

fi

test命令:

test  condition    测试参数和值

if  test  condition ;  then

command

fi

例:

variable="hello"

if  test  $variable ;  then

echo "not empty";

else

echo "empty";

fi

方括号测试方式:

if  [  condition  ]  ; then

command

fi

注意:括号内部两边有空格

数值比较符号:

-eq    等于

-ge    大于等于

-gt    大于

-le    小于等于

-lt     小于

-ne    不等于

例:

if  [  $var1 -gt  $var2  ]  ; then

echo "hello";

fi

字符串比较符号:

=     等于

!=    不等于

>    大于,使用时加转义字符,如:\>

-n  string    检查长度是否为非0

-z  string    检查长度是否为0

例:

if  [  "hello"  \>  "hello1"  ]  ;  then

command

fi

注意:在比较大于小于的顺序时,表达式和test命令的排序方式和sort的排序方式不同

文件比较:

-d       检查文件是否为目录

-e       检查文件或目录是否存在

-f        检查文件是否为文件

-r        检查文件是否可读

-s        检查文件是否存在并非空

-w       检查文件是否可写

-x        检查文件是否可执行

-O       检查文件是否存在并熟当前用户所有

-G       检查文件是否存在,并默认组是当前用户

file  -nt  file1    检查文件file是否比file1新,文件不存在会报错,new then

file  -ot  file1    检查文件file是否比file1旧,文件不存在会报错,old then

例:

directory=/home/bin

if  [  -d $directory  ] ;  then

echo "It is dirctory"

fi

复合条件测试:

[  condition  ]  &&  [  condition  ]

[  condition  ]  ||  [  condition  ]

例:

if  [ -d  $HOME ]  &&  [  -w  $HOME/test  ] ; then

command

fi

使用双括号:

((  expression  ))    双括号命令比较时可以使用数学表达式

++    自增

--      自减

!        取反

~      位求反

**      幂运算

<

>>    右位移

&      位与

|        位或

&&    逻辑与

||        逻辑或

例:

if  ((  $val  **  2 > 9  ))  ;  then

command

fi

注意:双括号中的>号不用转义,单方括号才需要转义

双方括号:

[[  expression  ]]    同test与单方括号 [ ] 一样,但是比test多了一个匹配模式,但并不是所有的shell都支持双方括号

例:

if  [[  $USER  ==  r*  ]]  ;  then

command

fi

case命令:

case  variable   in

pattern1  |  pattern2  )

command ; ;

pattern3  )

command ; ;

*  )

command ; ;

esac

例:

case  $USER   in

hello  |   haha  )

command

command  ; ;

huhu  )

command ; ;

*  )

command ; ;

esac

总结:

if  command ;  then

if  test condition ;  then

if  [ condition ]  ;  then

if  ((  expression  )) ;  then    可使用数学表达式

if  [[  expression  ]] ;  then    可使用正则表达式,其他同 [ ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值