shell 中的if-then语句的结构为:
- 单条件
#if标志开始,当if后命令的返回码为0时执行then后的语句
if commands
then
commands
#注意还有结尾,标志最近的一个if的结束
fi
例如:
#!/bin/bash
#test if-then
if date
then
who
fi
#who执行成功,返回码为0,结果为:
2016年 06月 28日 星期二 23:04:11 CST
pzl tty7 2016-06-28 19:46 (:0)
- 全覆盖
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: 未找到命令
2016年 06月 28日 星期二 23:11:14 CST
- 嵌套以及多条件
#如果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
#result
行 4: date123: 未找到命令
2016年 06月 28日 星期二 23:21:52 CST
real 0m0.000s
user 0m0.000s
sys 0m0.000s