第四周是你的第一个“质变点”——从手工操作转向自动化思维。前面三周你反复敲的那些命令,这周要让它们自己运行,你只需要看结果。
第四周详细练习手册:Shell 脚本自动化
核心目标:写出第一个真正能用的系统巡检脚本,并通过定时任务让它每天自动执行。
第一天:Shell 脚本基础语法
练习 1:你的第一个脚本——Hello World
# 1. 创建脚本文件
[xtc@localhost ~]$ mkdir -p ~/scripts
[xtc@localhost ~]$ cd ~/scripts
[xtc@localhost scripts]$ vim hello.sh
# 2. 在 vim 里输入以下内容:
# 3. 保存退出后,给脚本加执行权限
[xtc@localhost scripts]$ chmod +x hello.sh
# 4. 运行
[xtc@localhost scripts]$ ./hello.sh
Hello, 我是xtc
当前时间是: Wed May 6 10:00:00 CST 2026
我在这个目录: /home/xtc/scripts
脚本结构强制规范(以后每个脚本都照这个来):
-
第一行
#!/bin/bash— 告诉系统用哪个解释器,不是注释,必须写 -
#开头 — 注释,给自己和同事看的 -
$(命令)— 命令替换,把命令的输出嵌入字符串
练习 2:变量
[xtc@localhost scripts]$ vim var-practice.sh
[xtc@localhost scripts]$ chmod +x var-practice.sh
[xtc@localhost scripts]$ ./var-practice.sh
练习 3:条件判断(if 语句)
[xtc@localhost scripts]$ vim if-practice.sh
#!/bin/bash
# 条件判断练习——检查磁盘使用率
# 获取根分区使用率的数值部分(去掉百分号)
disk_usage=$(df -h / | tail -1 | awk '{print $5}' | sed 's/%//')
echo "当前根分区使用率: ${disk_usage}%"
# if 判断语法:[ 条件 ] 里面必须有空格!
if [ "$disk_usage" -gt 80 ]; then
echo "【警告】磁盘使用率超过 80%,请及时清理!"
elif [ "$disk_usage" -gt 60 ]; then
echo "【注意】磁盘使用率超过 60%,建议关注"
else
echo "【正常】磁盘使用率在安全范围内"
fi
[xtc@localhost scripts]$ chmod +x if-practice.sh
[xtc@localhost scripts]$ ./if-practice.sh
条件判断速查表:
| 数字比较 |
字符串比较 |
文件检查 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
练习 4:循环(for 循环)
[xtc@localhost scripts]$ vim for-practice.sh
#!/bin/bash
# 循环练习——批量检查和操作
echo "==================== 批量 ping 测试 ===================="


3586

被折叠的 条评论
为什么被折叠?



