Shell 流程控制
核对 Shell 不可为空分支的语法特性,以及 if/elif/else、for、while、until、case...esac 与 break/continue 循环控制结构。
学完这一章,你能够
- 核对 Shell 不可为空分支的语法特性,以及 if/elif/else、for、while、until、case...esac 与 break/continue 循环控制结构。
条件分支 if / elif / else 与非空规则
与 Java、PHP 等允许空 `{}` 代码块的语言不同,Shell(`sh`/`bash`)的流程控制分支不可为空:若 `else` 分支没有要执行的语句,就必须省略 `else`(否则会触发语法错误;如确需占位则应写入空命令 `:`)。本站 GNU bash 5.2.15 实测执行 `bash -n -c 'if true; then echo ok; else fi'` 确认为非零语法错误。
`if` 结构包含 `if ... then ... fi`、`if ... else ... fi` 与多路 `if ... elif ... else ... fi` 三种形式,其中 `fi` 为 `if` 倒写结束符,在终端单行书写时用分号分隔(如 `if [ ... ]; then echo "true"; fi`)。在 `[ ... ]` 中整数大小须用 `-gt`/`-lt`,而在 `(( ... ))` 算术判断中可直接写 `>`/`<`;`if` 亦常与 `test` 结合使用(现代脚本建议以 `$((...))` 替代已废弃的 `$[...]` 算术写法)。实测 `a=10, b=20` 在 `[ ... ]` 与 `(( ... ))` 下均命中 `lt` 分支,`test` 比较 `2*3` 与 `1+5` 命中相等分支。
for 循环与 while / until 循环
`for var in item1 item2 ...; do ... done` 逐项取出列表元素执行循环体,列表支持字面数字、单词、命令替换与文件名通配;若省略 `in 列表`,`for` 默认遍历当前脚本或函数的位置参数 `"$@"`。实测依次遍历 `1..5` 得 `12345`、遍历 `This is a string` 得四词序列,省略 `in` 的函数遍历 `alpha beta gamma` 准确输出三项。
`while condition; do ... done` 在条件为真时持续执行:既可配合 `while (( int <= 5 ))` 与 Bash `let "int++"`(算术表达式内变量无需 `$` 前缀)按次数计数,也可借助 `while read -r var` 逐行读取标准输入直至遇到文件结束符 EOF(终端按 `Ctrl-D`)。无限循环有 `while :`、`while true` 与 C 风格 `for (( ; ; ))` 三种常见写法。
`until condition; do ... done` 与 `while` 逻辑相反:只要条件返回假(非零)就继续循环,一旦条件变为真(`0`)则跳出。尽管多数场景下 `while` 更直观,但在等待某条件成立(如轮询就绪状态)时 `until` 语义更贴切。实测 `until [ ! "$u" -lt 10 ]` 准确输出 `0123456789`。
多路选择 case...esac 与 break / continue
`case 值 in 模式1) ... ;; ... esac` 是 Shell 的多分支模式匹配语句(`esac` 为 `case` 倒写):每个模式以右括号 `)` 结尾,分支末尾用双分号 `;;` 结束匹配(类似 C 的 `break`),支持 `|` 组合多模式并以 `*` 兜底捕获未匹配项。实测数字分支 `3` 命中 `three`、`9` 落入 `*` 得 `other`,字符串分支准确匹配 `portal`。
循环内提前干预流程使用 `break` 与 `continue`:`break` 立即跳出当前循环(可带层级参数跳出多层嵌套),不再处理后续迭代;`continue` 则仅跳过本轮剩余语句并直接进入下一轮条件判定。实测向同一输入流 `3, 7, 2` 分别施加 `break` 与 `continue`:`break` 在遇 `7` 后立即终止(不处理 `2`),输出 `ok:3;end:7;`;`continue` 在遇 `7` 时跳过紧随其后的不可达语句并继续处理 `2`,输出 `ok:3;skip:7;ok:2;`。
运行 GNU bash 5.2 if/for/while/until/case 与 break/continue 全流程控制实测
#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C.UTF-8
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT
VERSION="Debian bookworm-slim GNU bash 5.2.15 (--network none)"
CASES=()
json_str() {
local s="$1"
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\n'/\\n}
s=${s//$'\r'/\\r}
s=${s//$'\t'/\\t}
printf '"%s"' "$s"
}
add_case() {
local name="$1" summary="$2" expected="$3" actual="$4"
local passed="false"
if [[ "$expected" == "$actual" ]]; then
passed="true"
fi
CASES+=("{\"name\":$(json_str "$name"),\"summary\":$(json_str "$summary"),\"expected\":$(json_str "$expected"),\"actual\":$(json_str "$actual"),\"passed\":$passed}")
}
emit_json() {
printf '{"version":%s,"cases":[' "$(json_str "$VERSION")"
local i
for ((i = 0; i < ${#CASES[@]}; i++)); do
if ((i > 0)); then printf ','; fi
printf '%s' "${CASES[$i]}"
done
printf ']}\n'
}
# Case 1: if_elif_else_and_test - [ ], (( )), test, one-liner, empty else syntax error check
a=10; b=20
if [ "$a" -eq "$b" ]; then r_br="eq"
elif [ "$a" -gt "$b" ]; then r_br="gt"
elif [ "$a" -lt "$b" ]; then r_br="lt"
else r_br="other"
fi
if (( a == b )); then r_ar="eq"
elif (( a > b )); then r_ar="gt"
elif (( a < b )); then r_ar="lt"
else r_ar="other"
fi
num1=$((2 * 3)); num2=$((1 + 5))
r_test=$(if test "$num1" -eq "$num2"; then echo "eq"; else echo "ne"; fi)
r_one=$(if [ "$a" -lt "$b" ]; then echo "true"; fi)
set +e
bash -n -c 'if true; then echo ok; else fi' >/dev/null 2>&1
rc_empty_else=$?
set -e
add_case \
"if_elif_else_and_test" \
"验证 if/elif/else、(( ))、test、单行 if,以及空 else 分支触发语法错误(非零退出)" \
"br=lt;ar=lt;test=eq;one=true;empty_else_err=1" \
"br=${r_br};ar=${r_ar};test=${r_test};one=${r_one};empty_else_err=$((rc_empty_else != 0 ? 1 : 0))"
# Case 2: for_loop_lists_and_positional - numeric list, word list, one-liner, omitted in
nums=""
for loop in 1 2 3 4 5; do nums+="${loop}"; done
words=""
for str in This is a string; do words+="${str}/"; done
iter_pos() {
local out=""
for item; do out+="${item},"; done
printf '%s' "$out"
}
pos_res=$(iter_pos alpha beta gamma)
add_case \
"for_loop_lists_and_positional" \
"验证 for 遍历数字列表、单词列表及省略 in 子句时默认遍历位置参数" \
"nums=12345;words=This/is/a/string/;pos=alpha,beta,gamma," \
"nums=${nums};words=${words};pos=${pos_res}"
# Case 3: while_and_until_loops - while (( )), let, while read EOF, until 0..9
int=1; w_nums=""
while (( int <= 5 )); do
w_nums+="${int}"
let "int++"
done
read_out=""
while read -r site; do
read_out+="[${site}]"
done <<'EOF'
Linux
Bash
EOF
u=0; u_nums=""
until [ ! "$u" -lt 10 ]; do
u_nums+="${u}"
u=$(expr "$u" + 1)
done
add_case \
"while_and_until_loops" \
"验证 while (( )) 配合 let 计数、while read 读至 EOF 以及 until 输出 0~9" \
"w=12345;read=[Linux][Bash];u=0123456789" \
"w=${w_nums};read=${read_out};u=${u_nums}"
# Case 4: case_esac_patterns - numeric 1..4/*, string matching, multi-pattern a|b
match_num() {
case "$1" in
1) echo "one" ;;
2) echo "two" ;;
3) echo "three" ;;
4) echo "four" ;;
*) echo "other" ;;
esac
}
match_site() {
case "$1" in
"portal") echo "Portal" ;;
"google") echo "Google" ;;
"shop") echo "Shop" ;;
*) echo "Unknown" ;;
esac
}
add_case \
"case_esac_patterns" \
"验证 case...esac 多分支数字匹配、默认通配 * 分支及字符串分支匹配" \
"n3=three;n9=other;s=Portal" \
"n3=$(match_num 3);n9=$(match_num 9);s=$(match_site portal)"
# Case 5: break_and_continue_control - break exits infinite loop; continue skips trailing statement
brk_log=""
while read -r n; do
case "$n" in
1|2|3|4|5) brk_log+="ok:${n};" ;;
*) brk_log+="end:${n};"; break ;;
esac
done <<'EOF'
3
7
2
EOF
cont_log=""
while read -r n; do
case "$n" in
1|2|3|4|5) cont_log+="ok:${n};" ;;
*)
cont_log+="skip:${n};"
continue
cont_log+="UNREACHABLE;"
;;
esac
done <<'EOF'
3
7
2
EOF
add_case \
"break_and_continue_control" \
"验证 break 立即终止循环(不再处理后续 2),continue 跳过本轮后续语句但继续处理后续输入" \
"brk=ok:3;end:7;;cont=ok:3;skip:7;ok:2;" \
"brk=${brk_log};cont=${cont_log}"
emit_json
- 验证空 else 语法报错、if/elif/else 与 (( ))/test、for 列表与位置参数、while/until 计数与读流、case 模式匹配,以及 break 与 continue 对序列 3,7,2 的行为分歧。
所需环境:本地离线 Docker 容器(debian:bookworm-slim,GNU bash 5.2.15,--network none)。
当前源码 SHA256:fc02dcc237d6bc329e3f86b2bf0b24b92d87aaae7feeaa38cbe6eedfba4359ea
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(debian:bookworm-slim,GNU bash 5.2.15,--network none)。
ZIP SHA256:cc8998340caa076e9b21a759ad44ac7d8b7e82b4d8d6082a4ef986e47882c7ea
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在 Shell 中写出 if cond; then ... else fi 会报错?如果需要保留空分支占位应怎么写?
展开参考解答
Shell 语法要求 then、else、do 等子句体内至少包含一条命令;若暂时无需执行操作,可省略 else 分支,或在分支体内写入空命令冒号(:)作为合法占位。