shell编程-结构化命令

1、if-then语句

如果command命令执行成功(退出状态码为0),then部分的命令就会执行
if comand
then
    commands
fi

if comand: then
    commands
fi

例如:
#!/bin/bash
if date
who
then
        echo this is test
        date
fi

结果:
[root@localhost bin]# ./r.txt 
Thu Mar 30 14:51:35 EDT 2017
wcy      pts/0        2017-03-30 10:46 (192.168.0.100)
wcy      pts/1        2017-03-30 13:47 (192.168.0.100)
this is test
Thu Mar 30 14:51:35 EDT 2017

2、if-then-else语句

如果command命令执行成功(退出状态码为0),then部分的命令就会执行,否则执行else部分
if comand
then
    commands
else
    commands
fi

3、嵌套if

if comand1
then
    commands
elif command2
then
    commands
elif command3
then
    commands
fi


4、test命令

test condition
可以判断三类条件:数值比较、字符串比较、文件比较
如果条件成立,test命令退出并返回退出状态码0,否则返回1

在if-then语句中使用:
if test  condition
then
    commands
fi

if [ condition ]  #方括号内要有一个空格
then
    commands
fi

复合条件:[ condition ] && [ condition ]   [ condition ] || [ condition ]

5、if-then的高级特性

双尖括号:(( expression ))  用于数学表达式,
expression可以是任意的数学赋值或比较表达式,括号内的大于号不用转义

双方括号:[[ expression ]]  用于高级字符串处理功能,


6、case命令

case variable in
pattern1 | pattern2) commands1;;
pattern3) commands1;;
*) default commands1;;
esac

例如:
#!/bin/bash
case $USER in
root | ww)
        echo "welcome,$USER"
        date;;
wcy)
        echo "welcome,$USER";;
*) 
        echo "Sorry,you are not allowed here";;
esac

结果:
[root@localhost bin]# ./r.txt 
welcome,wcy 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

棉花糖老丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值