shell中的if-then语句

shell 中的if-then语句的结构为:

  1. 单条件
#if标志开始,当if后命令的返回码为0时执行then后的语句
if commands
then
    commands
#注意还有结尾,标志最近的一个if的结束
fi

例如:

#!/bin/bash
#test if-then
if date
then
        who
fi
#who执行成功,返回码为0,结果为:
20160628日 星期二 23:04:11 CST
pzl      tty7         2016-06-28 19:46 (:0)
  1. 全覆盖
if commands
#判断成功时执行then后的语句
then
    commands
#判断不成功时执行else后的语句
else
    commands
fi

例如:

#!/bin/bash
#test if-then
#不存在date123命令,所以不执行then,而执行else
if date123
then
        who
else
        date
fi
#返回结果为:4: date123: 未找到命令
20160628日 星期二 23:11:14 CST
  1. 嵌套以及多条件
#如果command1执行成功
if command1
#则执行commands2
then
    commands2
#如果command1执行不成功,则执行command3
elif command3
#如果command3执行成功
then
    commands4
#如果command3执行不成功,则执行command5
else
    commands5
fi

a simple example:

#!/bin/bash
#test if-then

if date123
then
        who

elif date
then
        time
else
        sl
fi
#result4: date123: 未找到命令
20160628日 星期二 23:21:52 CST

real    0m0.000s
user    0m0.000s
sys 0m0.000s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值