Linux Shell 脚本从 0 到 1:一篇就能写生产代码

01 先跑起来:30 秒脚本「Hello World」

把下面 4 行粘进终端,立刻体会脚本的魅力:

#!/bin/bash
# hello.sh
echo "今天是 $(date +%F)"

给脚本权限
chmod +x hello.sh && ./hello.sh

跑通即掌握三大件:
Shebang → 变量 → 执行权限


02 脑图:一张图记住全部语法


03 语法速查表(复制即可用)


功能
模板
备注
变量name="tom"
 / eC++ho $name
等号两侧无空格
数组arr=(a b c)
 / echo ${arr[0]}
@
 遍历
字符串${#str}
 长度 / ${str:0:3} 截取

ifif [ "$a" -gt 10 ]; then … fi
中括号前后空格
forfor f in *.log; do echo $f; done
whilewhile read line; do … done < file
函数deploy(){ Git pull && npm run build; }deploy
 直接调用
测试文件[ -f /etc/passwd ]
 / -d 目录 / -x 可执行


04 15 个生产级场景脚本

每个脚本都可直接落地,保存为 xxx.shchmod +x 即可运行。

1️⃣ 目录增量备份

#!/bin/bash
# backup.sh
SRC=/data
DST=/backup/$(date +%F).tar.gz
tar -czf "$DST" "$SRC" --exclude='*.tmp'
echo "✅ 备份完成:$DST"

2️⃣ 日志分卷 + 自动清理

#!/bin/bash
# log_cleanup.sh
LOGDIR=/var/log/app
find "$LOGDIR" -name "*.log" -mtime +7 -exec gzip {} \;
find "$LOGDIR" -name "*.gz"  -mtime +30 -delete

3️⃣ CPU / 内存告警(微信/钉钉)


#!/bin/bash
# alert.sh
CPU=$(top -bn1 | awk '/Cpu/ {printf "%.0f", 100-$8}')
MEM=$(free | awk '/Mem/ {printf "%.0f", $3/$2*100}')

# 报警阈值
CPU_THRESHOLD=80
MEM_THRESHOLD=85

WEBHOOK="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY"

msg="CPU ${CPU}% MEM ${MEM}%"
if (( CPU > CPU_THRESHOLD )) || (( MEM > MEM_THRESHOLD )); then
    curl -sS -X POST "$WEBHOOK" \
         -H 'Content-Type: application/json' \
         -d "{\"msgtype\":\"text\",\"text\":{\"content\":\"⚠️ 资源告警:$msg\"}}"
fi