文章目录
简单的if结构
(如果满足if后面的表达式expression为真0,则执行command命令,然后退出,不满足就不执行command,直接退出)
if expression
then
command
fi
或则
if expression;then
command
fi
例子(判断一个输入是否为空,并用exit返回指定值)
#!/bin/bash
echo "请输入一个字符串"
read a
if [ -z "$a" ];then
echo "对不起,你未输入字符串"
exit 1
fi
if/else简单结构
(如果满足if后面的表达式,则执行command1,如果不满足表达式,则执行else后面的command2命令)
if expression;then
command1
else
command2
fi
if/else嵌套
(可以判断多个条件,注意不要漏掉fi)
if expression1;then
if expression2;then
command1
else
command2
fi
else
commadn3
fi
if/elif/else结构
(用来解决上面那种容易漏掉fi的情况,提升可读性)
if expression1;then
command1
elif expression2;then
command2
elif expression3;then
command3
else
command4
fi
case结构
(同样适用于多分支结构)
case variable in
value1)
command1
command2;;
value2)
command2;;
value3)
command3;;
.......
*)
command;;
esac
例子
case "$mouth" in
1)
echo "this is 1 月";;
2)
echo "this is 2 月";;
.........
12)
echo "this is 12 月";;
*)
echo "数字错误";;
esac
如果文章对你有帮助,欢迎点击上方按钮打赏作者
暂无评论