11. 字符串操作实例(101-150)
字符串截取与分割
# 101. 截取字符串前N个字符
str="hello world"
echo "${str:0:5}"  # 输出: hello# 102. 从右边截取
echo "${str: -5}"  # 输出: world# 103. 删除字符串前缀
filename="backup_20231001.tar.gz"
echo "${filename#backup_}"  # 输出: 20231001.tar.gz# 104. 删除字符串后缀
echo "${filename%.tar.gz}"  # 输出: backup_20231001# 105. 替换字符串中的字符
echo "${str//o/O}"  # 输出: hellO wOrld
字符串长度与判断
# 106. 获取字符串长度
str="hello"
echo "${#str}"  # 输出: 5# 107. 检查字符串是否为空
if [[ -z "$str" ]]; thenecho "字符串为空"
fi# 108. 检查字符串是否包含子串
if [[ "$str" == *"ell"* ]]; thenecho "包含ell"
fi# 109. 字符串大小写转换
echo "${str^^}"  # 转大写: HELLO
echo "${str,,}"  # 转小写: hello# 110. 字符串反转
echo "hello" | rev  # 输出: olleh
12. 数组操作实例(151-200)
数组基础操作
# 151. 定义数组
fruits=("apple" "banana" "cherry" "date")# 152. 访问数组元素
echo "${fruits[0]}"  # apple
echo "${fruits[@]}"   # 所有元素# 153. 数组长度
echo "${#fruits[@]}"  # 4# 154. 数组遍历
for fruit in "${fruits[@]}"; doecho "水果: $fruit"
done# 155. 数组切片
echo "${fruits[@]:1:2}"  # banana cherry
数组高级操作
# 156. 添加数组元素
fruits+=("elderberry")# 157. 删除数组元素
unset fruits[1]# 158. 数组排序
sorted=($(printf "%s\n" "${fruits[@]}" | sort))# 159. 关联数组(bash 4.0+)
declare -A user=([name]="John" [age]=30 [city]="NYC")
echo "${user[name]}"# 160. 数组合并
arr1=(1 2 3)
arr2=(4 5 6)
combined=("${arr1[@]}" "${arr2[@]}")
13. 正则表达式实例(201-250)
基础正则匹配
# 201. 邮箱地址验证
email="user@example.com"
if [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; thenecho "有效邮箱"
fi# 202. IP地址验证
ip="192.168.1.1"
if [[ "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; thenecho "有效IP"
fi# 203. 数字匹配
if [[ "123" =~ ^[0-9]+$ ]]; thenecho "纯数字"
fi# 204. 提取匹配分组
text="Date: 2023-10-01"
if [[ "$text" =~ ([0-9]{4}-[0-9]{2}-[0-9]{2}) ]]; thenecho "日期: ${BASH_REMATCH[1]}"
fi# 205. 多条件匹配
if [[ "$file" =~ \.(txt|log|csv)$ ]]; thenecho "文本文件"
fi
14. 文件系统高级操作(251-300)
文件属性操作
# 251. 检查文件类型
[[ -f "file.txt" ]] && echo "普通文件"
[[ -d "dir" ]] && echo "目录"
[[ -L "link" ]] && echo "符号链接"# 252. 检查文件权限
[[ -r "file.txt" ]] && echo "可读"
[[ -w "file.txt" ]] && echo "可写"
[[ -x "file.txt" ]] && echo "可执行"# 253. 获取文件详细信息
stat file.txt
ls -i file.txt  # inode号# 254. 文件时间戳操作
touch -t 202310011200.00 file.txt  # 设置特定时间
touch -r reference.txt target.txt  # 同步时间戳# 255. 文件锁定操作
(flock -x 200# 临界区代码echo "操作文件"
) 200>/var/lock/mylockfile
15. 网络编程实例(301-350)
Socket编程
# 301. 简单的TCP服务器
nc -l 8080# 302. TCP客户端连接
echo "Hello" | nc localhost 8080# 303. UDP通信
nc -u -l 8080  # UDP服务器
echo "Hello" | nc -u localhost 8080  # UDP客户端# 304. 端口占用检查
netstat -tulpn | grep :8080
ss -tulpn | grep :8080# 305. HTTP服务器
while true; do { echo -e "HTTP/1.1 200 OK\r\n"; echo "Hello World"; } | nc -l 8080
done
网络监控
# 306. 监控网络连接
watch -n 1 'netstat -an | grep ESTABLISHED'# 307. 带宽监控
iftop
nethogs# 308. 网络流量统计
vnstat -d  # 每日流量
vnstat -m  # 每月流量# 309. 实时网速监控
while true; dorx1=$(cat /sys/class/net/eth0/statistics/rx_bytes)tx1=$(cat /sys/class/net/eth0/statistics/tx_bytes)sleep 1rx2=$(cat /sys/class/net/eth0/statistics/rx_bytes)tx2=$(cat /sys/class/net/eth0/statistics/tx_bytes)echo "下载: $(( (rx2 - rx1) / 1024 )) KB/s 上传: $(( (tx2 - tx1) / 1024 )) KB/s"
done
16. 性能优化脚本(351-400)
系统性能监控
# 351. CPU使用率监控
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)# 352. 内存使用监控
mem_total=$(free | awk '/Mem:/ {print $2}')
mem_used=$(free | awk '/Mem:/ {print $3}')
mem_percent=$((mem_used * 100 / mem_total))# 353. 磁盘IO监控
iostat -x 1 1# 354. 系统负载监控
load_avg=$(uptime | awk -F'load average:' '{print $2}' | cut -d',' -f1)# 355. 性能监控脚本
monitor_system() {while true; doclearecho "=== 系统监控 ==="echo "时间: $(date)"echo "负载: $(uptime | awk -F'load average:' '{print $2}')"echo "内存: $(free -h | awk '/Mem:/ {print $3 "/" $2}')"echo "磁盘: $(df -h / | awk 'NR==2 {print $3 "/" $2 " (" $5 ")"}')"sleep 5done
}
17. 安全相关脚本(401-450)
安全检测
# 401. SSH登录监控
tail -f /var/log/auth.log | grep sshd# 402. 检查可疑进程
ps aux | awk '$3 > 50.0 {print $0}'  # CPU使用率超过50%# 403. 文件完整性检查
find /etc -type f -exec md5sum {} \; > /var/log/etc_checksums.txt# 404. 端口扫描检测
netstat -an | grep LISTEN | awk '{print $4}' | cut -d':' -f2 | sort -nu# 405. 用户登录审计
last | head -20
who /var/log/wtmp
安全加固
# 406. 检查密码过期
chage -l username# 407. 检查空密码用户
awk -F: '($2 == "" ) {print $1}' /etc/shadow# 408. 检查SUID文件
find / -perm -4000 -type f 2>/dev/null# 409. 防火墙规则检查
iptables -L -n
ufw status# 410. 自动安全更新
apt-get update && apt-get upgrade -y
18. 跨平台兼容脚本(451-500)
系统检测与兼容
# 451. 检测操作系统
if [[ "$OSTYPE" == "linux-gnu"* ]]; thenecho "Linux系统"
elif [[ "$OSTYPE" == "darwin"* ]]; thenecho "macOS系统"
elif [[ "$OSTYPE" == "cygwin" ]]; thenecho "Cygwin (Windows)"
fi# 452. 检测Shell类型
echo "当前Shell: $SHELL"
echo "Shell版本: $BASH_VERSION"# 453. 路径兼容处理
normalize_path() {if [[ "$OSTYPE" == "darwin"* ]]; thenecho "$1" | sed -E 's#/+#/#g'elseecho "$1" | sed -r 's#/+#/#g'fi
}# 454. 命令存在性检查
command_exists() {command -v "$1" >/dev/null 2>&1
}# 455. 跨平台文件锁
lock_file() {local lockfile="$1"if command_exists flock; thenflock -x 200else# 使用mkdir作为原子操作while ! mkdir "$lockfile.lock" 2>/dev/null; dosleep 1donefi
}
19. 数据库操作实例(501-550)
MySQL操作
# 501. 连接MySQL执行查询
mysql -u user -ppassword -e "SELECT * FROM table" database# 502. 批量执行SQL文件
mysql -u user -ppassword database < script.sql# 503. 数据库备份
mysqldump -u user -ppassword --databases db1 db2 > backup.sql# 504. 检查MySQL状态
mysqladmin -u user -ppassword status# 505. 数据库监控
mysql -u user -ppassword -e "SHOW PROCESSLIST;"
PostgreSQL操作
# 506. PostgreSQL连接查询
psql -U user -d database -c "SELECT * FROM table"# 507. 导出查询结果到CSV
psql -U user -d database -c "COPY (SELECT * FROM table) TO STDOUT WITH CSV HEADER" > output.csv# 508. PostgreSQL备份
pg_dump -U user database > backup.sql# 509. 数据库大小查询
psql -U user -d database -c "SELECT pg_size_pretty(pg_database_size('database'));"# 510. 表空间监控
psql -U user -d database -c "SELECT schemaname,tablename,pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) FROM pg_tables ORDER BY 3 DESC;"
20. Web服务监控实例(551-600)
Web服务检查
# 551. 网站可用性检查
check_website() {local url="$1"if curl -s --head --fail "$url" >/dev/null; thenecho "✓ $url 可访问"return 0elseecho "✗ $url 不可访问"return 1fi
}# 552. 监控HTTP响应时间
measure_response_time() {local url="$1"local start=$(date +%s%N)curl -s -o /dev/null -w "%{http_code}" "$url" >/dev/nulllocal end=$(date +%s%N)local duration=$(( (end - start) / 1000000 ))echo "响应时间: ${duration}ms"
}# 553. SSL证书过期检查
check_ssl_cert() {local domain="$1"local port="${2:-443}"echo | openssl s_client -servername "$domain" -connect "$domain:$port" 2>/dev/null | openssl x509 -noout -dates
}# 554. 网站内容监控
monitor_website_content() {local url="$1"local pattern="$2"if curl -s "$url" | grep -q "$pattern"; thenecho "内容包含: $pattern"elseecho "内容不包含: $pattern"fi
}# 555. API端点监控
check_api() {local endpoint="$1"local expected_status="${2:-200}"local actual_status=$(curl -s -o /dev/null -w "%{http_code}" "$endpoint")if [[ "$actual_status" -eq "$expected_status" ]]; thenecho "✓ API正常 (状态码: $actual_status)"elseecho "✗ API异常 (状态码: $actual_status, 期望: $expected_status)"fi
}