08 · 流程控制
目标:掌握 if / for / while / until / case 五件套
🎯 今天要带走的三件事
if必须以fi结尾(fi=if倒过来)for ... do ... done、case ... esac(esac=case倒过来)- sh 的流程控制不可为空 ——
else分支没内容就别写
一、if 语句
⚠️ 与 Java/PHP 不同,sh 的流程控制不可为空。if 分支没语句就不写 else。
if
if condition
then
command1
commandN
fi
一行写法:
if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi
if else
if condition
then
command1
else
command
fi
if else-if else
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
两种判断写法对比:
# 单方括号:用 -gt / -lt
if [ "$a" -gt "$b" ]; then ... fi
# 双方括号:直接用 > <
if (( a > b )); then ... fi
与 test 结合:
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo '两个数字相等!'
else
echo '两个数字不相等!'
fi
二、for 循环
for var in item1 item2 ... itemN
do
command1
commandN
done
一行:for var in item1 item2; do command1; done
# 遍历数字
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
# 遍历字符串(按空格拆分)
for str in This is a string
do
echo $str
done
# 输出:This / is / a / string
in列表可省略 —— 省略时循环使用命令行的位置参数。
三、while 循环
while condition
do
command
done
#!/bin/bash
int=1
while(( $int<=5 ))
do
echo $int
let "int++"
done
# 输出 1~5
读取键盘输入(Ctrl-D 结束):
echo -n '输入你最喜欢的网站名: '
while read FILM
do
echo "是的!$FILM 是一个好网站"
done
无限循环三种写法:
while :
do ... done
while true
do ... done
for (( ; ; ))
四、until 循环
与 while 处理方式相反:条件为 false 时继续,为 true 时停止。
until condition
do
command
done
#!/bin/bash
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
# 输出 0~9
一般 while 更常用,until 只在极少数场景更顺手。
五、case ... esac(多分支)⭐
类似其他语言的 switch ... case。
case 值 in
模式1)
command1
;;
模式2)
command2
;;
esac
规则:
- 取值后必须跟单词 in
- 每个模式以 右括号 ) 结束
- ;; 等同于 break,跳出整个 case
- 无匹配时用 * 捕获
echo '输入 1 到 4 之间的数字:'
read aNum
case $aNum in
1) echo '你选择了 1'
;;
2) echo '你选择了 2'
;;
*) echo '你没有输入 1 到 4 之间的数字'
;;
esac
esac就是case反过来拼写。
六、跳出循环
| 命令 | 作用 |
|---|---|
break |
跳出所有循环(终止后面的所有循环) |
continue |
只跳出当前这一轮循环 |
while :
do
echo -n "输入 1 到 5 之间的数字:"
read aNum
case $aNum in
1|2|3|4|5) echo "你输入的数字为 $aNum!"
;;
*) echo "不是 1 到 5,游戏结束"
break
;;
esac
done
🌙 今日作业
- [ ] 用
for打印 1~10 的数字 - [ ] 用
case写一个简单菜单(1.查磁盘 2.列进程 3.退出)
自测题
if块用什么结尾?case块呢?until和while的区别?break和continue的区别?
👉 参考答案
1. `if` → `fi`;`case` → `esac`(都是关键字反写)。 2. while:条件为真时执行;until:条件为假时执行,为真则停止。处理逻辑相反。 3. break 跳出整个循环;continue 只跳过本轮,进入下一轮。🔗 关联
Shell-学习总览|上一课 → 07-test命令与条件测试|下一课 → 09-函数