【shell编程学习】结构化if命令

一、使用if-then语句

格式:

if comand

then

      commands

fi

或者下种格式:

if command;then

    commands

fi

检查command命令执行成功($?),则执行then后面的指令


二、使用if-then-else语句

格式:

if command

then

    commands

else

    commands

fi

或者下述格式

if comand;then

    commands

else

    commands

fi

如果command执行成功,则执行then后面的语句,否则执行else后面的语句


三、嵌套if

格式如下

if command1

then

    commands

elif command2

then 

    commands

elif command3

 then

    commands

fi


四、test命令

上述if后面的条件都是和命令行执行结果相关的,下述的判断条件与命令行执行无关。

格式

 if test condition

then

commands

fi

或下面格式

if  [ condition ]

then

commands

fi

condition可以判断三种条件:

1、数据比较

2、字符串比较

3、文件比较

 

4.1 数据比较

condition数值比较指令
 比        较   描      述
n1  -eq  n2 检查n1 n2是相等
n1  -ge  n2 检查n1是否大于等n2
n1  -gt   n2检查n1是否大于n2
n1   -le  n2检查n1是否小于等于n2
n1   -lt   n2检查n1是否小于n2
n1  -ne  n2检查n1 是否不等于n2

example:

var1=1

var2=2

if  [ $var1 -eq $var2 ];then

  echo var1 is not equal to var2

fi


4.2  字符串比较

字符串比较功能
比  较描述
 str1 = str2检查字符串str1和str2是否相同
str1 != str2检查字符串str1和str2是否不相同
str1 < str2检查字符串str1是否比str2小
str1 > str2检查字符串str1是否比str2大
-n str1检查字符串str1是否为非空
-z str1检查字符串str1是否为空

example:
str1=hello

str2=world

if [ $str1 = $str2 ];then

echo str1 is not equal to str2

fi


str1=''

if [ -n $str1 ];then

echo str1 is not empty

fi

4.3 文件比较

文件比较功能
比较描述
-d file检查file是否存在并且是目录
-e file检查file是否存在
-f file检查file是否存在并且是个文件
-r fle检查file是否存在并可读
-w file检查文件file是否存在并可写
-x file检查文件file是否存在并可执行
-s file检查文件是否存在并且非空
-O file检查文件file是否存在并归当前用户所有
-G file检查file是否存在并且默认组与当前用户相同
file1 -nt file2检查file1是否比file2新
file1 -ot file2检查file1是否比file2旧

五、复合测试条件

格式如下:
1、 [ condition1 ]  || [ condition2 ]
2、 [ condition1 ] && [ condition2 ]

六、if-then高级特性

6.1 使用双圆括号

双圆括号允许将高级表达式放在比较中,格式如下

(( expression ))

6.2 使用双方括号

[[ expression ]]

支持正则表达式里的模式匹配 

example:
if [[ $USER == r* ]]

then

echo $USER

else

    echo "sorry to konw"

fi

七、case命令

case命令格式如下:

case variable in

pattern1 | pattern2)

commands;;

pattern3) commands;;

*) commands;;

esac





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值