# Shell流程控制
## if-else语句的几种格式
**格式一**
语法格式
```shell
if condition
then
command1
command2
...
commandN
fi
```
写成一行
```shell
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
```
**格式二**
语法格式
```shell
if condition1
then
command1
command2
...
commandN
else
command
fi
```
**格式三**
语法格式
```shell
if condition
then
command1
elif condition2
then
command2
else
command3
fi
```
## for循环
for循环一般格式为
```shell
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
```
写成一行格式为
```shell
for var in item1 item2 ... itemN; do command1; command2; ...; commandN; done
```
## while循环
while 循环用于不断执行一系列命令,也用于从输入文件中读取数据。其语法格式为
```shell
while condition
do
command
done
```
## until循环
until 循环执行一系列命令直至条件为 true 时停止,until 循环与 while 循环在处理方式上刚好相反。
```shell
until condition
do
command
done
```
## case选择
**case ... esac** 为多选择语句,与其他语言中的 switch ... case 语句类似,是一种多分支选择结构,每个 case 分支用右圆括号开始,用两个分号 **;;** 表示 break,即执行结束,跳出整个 case ... esac 语句,esac(就是 case 反过来)作为结束标记。
```shell
case 值 in
模式1)
command1
command2
...
commandN
;;
模式2)
command1
command2
...
commandN
;;
模式3)
command1
command2
...
commandN
;;
esac
```
case 工作方式如上所示,取值后面必须为单词 **in**,每一模式必须以右括号结束。取值可以为变量或常数,匹配发现取值符合某一模式后,其间所有命令开始执行直至 **;;**。取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。
```bash
echo "输入1到4之间的数字: "
read aNum
case ${aNum} in
1) echo "你选择了1"
;;
2) echo "你选择了2"
;;
3) echo "你选择了3"
;;
4) echo "你选择了4"
;;
*) echo "超出范围"
;;
esac
```
也可以匹配字符串
```shell
#!/bin/bash
site="wangyuedong"
case "${site}" in
"wang") echo "This is wang"
;;
"wangyuedong") echo "This is wangyuedong"
;;
"hahaha") echo "This is hahaha"
;;
esac
```