shell 脚本-分支控制
if
if…else
if else
的语法格式为
if condition
then
command_for_then_1
command_for_then_2
...
command_for_then_n
else
command_for_then_1
command_for_then_2
...
command_for_then_n
fi
以 if
开头, 如果条件成立则执行 then
, 条件不成立, 则执行 else
, 最终以 fi
结束
注意: else 分支不可为空. 例如:
# 错误写法
if condition
then
command_for_then_1
command_for_then_2
...
command_for_then_n
else
fi
如果不需要在 else
时执行任何命令, 可以直接不使用 else
if condition
then
command_for_then_1
command_for_then_2
...
command_for_then_n
fi
if…elif
当我们使用一个条件判断无法满足需求, 需要在 if
不成立的情况下再次判断时, 可以使用 elif
condition_1=false
condition_2=true
if $condition_1
then
echo 'condition_1 is true'
elif $condition_2
then
echo 'condition_1 is false, but condition_2 is true'
else
echo 'condition_1 and condition_2 is false'
fi
运行结果:
condition_1 is false, but condition_2 is true
case esac
case
为多分支选择, 用于判断一个表达式可能出现的多种情况需要做不同的处理
语法格式为 case val in value1) command... ;; value2) command... ;; ... valueN) command... ;; esac;
每个 case
分支用右圆括号开始,以两个分号 ;; 最终以 esac
为最终判断结束.
num=3
case $num in
1)
echo "num 为 1"
;;
2)
echo "num 为 2"
;;
3)
echo "num 为 3"
;;
4)
echo "num 为 4"
;;
esac
运行结果:
num 为 3
每个 case 的判断还可以使用 value1 | value2
同时匹配多个值, 或使用 *
匹配所有值
num=3
case $num in
1 | 2 | 3)
echo "num 为 1 或 2 或 3"
;;
4)
echo "num 为 4"
;;
*)
echo "num 非 1 ~ 4"
;;
esac
运行结果:
num 为 1 或 2 或 3
搭配 read
获取用户输入, 可以用来校验用户的输入内容
echo "请输入我的的名字: "
read name
case $name in
'eno')
echo "这是我的名字"
;;
'zeng')
echo "这是我的姓"
;;
*)
echo "输入错误"
;;
esac;