插件窝 干货文章 40个简单但有效的Linux Shell脚本示例

40个简单但有效的Linux Shell脚本示例

bash bin 脚本 file 601    来源:    2025-05-13

以下是40个实用且易上手的Linux Shell脚本示例,涵盖系统管理、文件操作、网络工具等场景,适合初学者和日常使用:


一、系统信息类

  1. 显示系统信息
#!/bin/bash
echo "Hostname: $(hostname)"
echo "Kernel: $(uname -r)"
echo "CPU: $(lscpu | grep 'Model name')"
echo "Memory: $(free -h | awk '/Mem/{print $2}')"
  1. 磁盘使用监控
#!/bin/bash
df -h | awk '$5 > 80% {print "警告: " $1 " 使用率 " $5}'
  1. 内存使用前10进程
#!/bin/bash
ps -eo pid,user,%mem,cmd --sort=-%mem | head -n 11

二、文件操作类

  1. 批量重命名文件(.txt → .bak)
#!/bin/bash
for file in *.txt; do mv "$file" "${file%.txt}.bak"; done
  1. 查找并删除空文件
#!/bin/bash
find /path/to/dir -type f -empty -delete
  1. 统计目录大小
#!/bin/bash
du -sh /path/to/directory
  1. 备份文件(带日期)
#!/bin/bash
cp important_file.txt important_file_$(date +%Y%m%d).bak

三、网络工具类

  1. 检查网站是否在线
#!/bin/bash
curl -Is http://example.com | head -n 1
  1. 批量ping测试
#!/bin/bash
for ip in 192.168.1.{1..10}; do ping -c 1 $ip &>/dev/null && echo "$ip is up"; done
  1. 下载文件并验证MD5
#!/bin/bash
wget http://example.com/file.zip && md5sum file.zip > file.zip.md5

四、自动化运维类

  1. 用户账户批量创建
#!/bin/bash
while read user; do useradd $user; done < users.txt
  1. 服务监控(自动重启Nginx)
#!/bin/bash
if ! systemctl is-active --quiet nginx; then systemctl restart nginx; fi
  1. 日志清理(保留7天)
#!/bin/bash
find /var/log -name "*.log" -mtime +7 -exec rm {} \;

五、实用小工具

  1. 随机密码生成器
#!/bin/bash
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 1
  1. 文件编码转换(GBK→UTF-8)
#!/bin/bash
iconv -f GBK -t UTF-8 input.txt -o output.txt
  1. SSH登录提醒
#!/bin/bash
echo "用户 $(whoami) 从 $(echo $SSH_CLIENT | awk '{print $1}') 登录" | mail -s "SSH登录提醒" admin@example.com

六、进阶示例

  1. 简易计算器
#!/bin/bash
echo "scale=2; $1 $2 $3" | bc
# 用法:./calc.sh 5 + 3
  1. 监控CPU温度
#!/bin/bash
sensors | grep 'Core 0' | awk '{print $3}'
  1. Git仓库自动更新
#!/bin/bash
cd /path/to/repo && git pull && git log -1
  1. Docker容器清理
#!/bin/bash
docker system prune -af

完整脚本模板

#!/bin/bash
# Script Name: example.sh
# Description: 简要描述脚本功能
# Author: Your Name
# Date: $(date +%F)

# 严格模式(推荐)
set -euo pipefail

# 变量定义
LOG_FILE="/var/log/myscript.log"

# 函数示例
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOG_FILE
}

# 主逻辑
main() {
    log "脚本开始执行"
    # 你的代码...
    log "脚本执行完成"
}

# 执行主函数
main "$@"

使用技巧

  1. 给脚本添加执行权限:chmod +x script.sh
  2. 调试脚本:bash -x script.sh
  3. 定时任务:通过crontab -e添加(示例每天凌晨执行): bash 0 0 * * * /path/to/script.sh

这些脚本可根据实际需求修改参数,建议先在小范围测试后再正式使用。