以下是几个常见的 Bash 脚本使用场景,适合初学者和进阶用户参考:
1. 文件批量重命名 ✅
#!/bin/bash
for file in *.txt; do
mv "$file" "${file%.txt}.bak"
done
该脚本会将当前目录下所有 .txt
文件扩展名为 .bak
,例如 example.txt
→ example.bak
2. 目录权限批量设置 📁
#!/bin/bash
chmod -R 755 /path/to/directory
使用 -R
参数递归修改目录内所有文件和子目录权限为 755
3. 自动化定时任务 🕰️
#!/bin/bash
# 将脚本添加到 crontab
(crontab -l 2>/dev/null; echo "0 2 * * * /path/to/script.sh") | crontab -
此脚本会设置每天凌晨 2 点执行 script.sh
的定时任务
如需深入了解 Bash 脚本编写规范,可访问 Bash 脚本教程