以下是40个实用且易上手的Linux Shell脚本示例,涵盖系统管理、文件操作、网络工具等场景,适合初学者和日常使用:
#!/bin/bash
echo "Hostname: $(hostname)"
echo "Kernel: $(uname -r)"
echo "CPU: $(lscpu | grep 'Model name')"
echo "Memory: $(free -h | awk '/Mem/{print $2}')"
#!/bin/bash
df -h | awk '$5 > 80% {print "警告: " $1 " 使用率 " $5}'
#!/bin/bash
ps -eo pid,user,%mem,cmd --sort=-%mem | head -n 11
#!/bin/bash
for file in *.txt; do mv "$file" "${file%.txt}.bak"; done
#!/bin/bash
find /path/to/dir -type f -empty -delete
#!/bin/bash
du -sh /path/to/directory
#!/bin/bash
cp important_file.txt important_file_$(date +%Y%m%d).bak
#!/bin/bash
curl -Is http://example.com | head -n 1
#!/bin/bash
for ip in 192.168.1.{1..10}; do ping -c 1 $ip &>/dev/null && echo "$ip is up"; done
#!/bin/bash
wget http://example.com/file.zip && md5sum file.zip > file.zip.md5
#!/bin/bash
while read user; do useradd $user; done < users.txt
#!/bin/bash
if ! systemctl is-active --quiet nginx; then systemctl restart nginx; fi
#!/bin/bash
find /var/log -name "*.log" -mtime +7 -exec rm {} \;
#!/bin/bash
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 1
#!/bin/bash
iconv -f GBK -t UTF-8 input.txt -o output.txt
#!/bin/bash
echo "用户 $(whoami) 从 $(echo $SSH_CLIENT | awk '{print $1}') 登录" | mail -s "SSH登录提醒" admin@example.com
#!/bin/bash
echo "scale=2; $1 $2 $3" | bc
# 用法:./calc.sh 5 + 3
#!/bin/bash
sensors | grep 'Core 0' | awk '{print $3}'
#!/bin/bash
cd /path/to/repo && git pull && git log -1
#!/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 "$@"
chmod +x script.sh
bash -x script.sh
crontab -e
添加(示例每天凌晨执行):
bash
0 0 * * * /path/to/script.sh
这些脚本可根据实际需求修改参数,建议先在小范围测试后再正式使用。