Shell 控制结构

学习条件判断、循环和分支控制,编写逻辑清晰的 Shell 脚本

条件判断

if 语句

#!/bin/bash
# 基本 if 语句
if [ $# -eq 0 ]; then
echo "没有提供参数"
fi
# if-else 语句
if [ $1 -gt 10 ]; then
echo "数字大于10"
else
echo "数字小于等于10"
fi

测试条件

数值比较
-eq等于
-ne不等于
-gt大于
-lt小于
字符串比较
=字符串相等
!=字符串不等
-z字符串为空
-n字符串非空

case 语句

基本语法

#!/bin/bash
case $1 in
"start")
echo "启动服务"
;;
"stop")
echo "停止服务"
;;
*)
echo "无效选项"
;;
esac

循环结构

for 循环

# 遍历列表
for item in apple banana orange; do
echo "水果: $item"
done
# 遍历文件
for file in *.txt; do
echo "处理文件: $file"
done

while 循环

# 基本while循环
count=1
while [ $count -le 5 ]; do
echo "计数: $count"
count=$((count + 1))
done

循环控制

break 和 continue

# break - 跳出循环
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
break
fi
echo "数字: $i"
done
# continue - 跳过当前迭代
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
continue
fi
echo "数字: $i"
done

实用示例

文件批处理脚本

#!/bin/bash
# 批量重命名文件
for file in *.jpg; do
if [ -f "$file" ]; then
newname="photo_$(date +%Y%m%d)_$file"
mv "$file" "$newname"
echo "重命名: $file -> $newname"
fi
done

菜单驱动脚本

#!/bin/bash
while true; do
echo "=== 系统管理菜单 ==="
echo "1) 查看系统信息"
echo "2) 查看磁盘使用"
echo "3) 退出"
read -p "请选择: " choice
case $choice in
1) uname -a ;;
2) df -h ;;
3) echo "再见!"; break ;;
*) echo "无效选项" ;;
esac
done

继续学习

掌握了控制结构后,继续学习更多 Shell 编程技能