本文目录导读:

基础Shell脚本(Linux/Unix)
文件压缩脚本
#!/bin/bash
# backup_compress.sh
# 定义变量
BACKUP_SRC="/path/to/source"
BACKUP_DST="/path/to/backup"
BACKUP_DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_NAME="backup_${BACKUP_DATE}.tar.gz"
# 创建备份目录
mkdir -p "$BACKUP_DST"
# 压缩文件
tar -czvf "${BACKUP_DST}/${BACKUP_NAME}" "$BACKUP_SRC"
# 检查是否成功
if [ $? -eq 0 ]; then
echo "=== 压缩完成: ${BACKUP_DST}/${BACKUP_NAME} ==="
else
echo "!!! 压缩失败 !!!"
exit 1
fi
# 显示结果
ls -lh "${BACKUP_DST}/${BACKUP_NAME}"
文件解压脚本
#!/bin/bash
# extract.sh
# 检查参数
if [ $# -eq 0 ]; then
echo "用法: $0 <压缩文件名> [目标目录]"
exit 1
fi
FILE="$1"
DEST="${2:-.}" # 默认解压到当前目录
# 检查文件是否存在
if [ ! -f "$FILE" ]; then
echo "错误: 文件 $FILE 不存在"
exit 1
fi
# 创建目标目录
mkdir -p "$DEST"
# 根据文件扩展名解压
case "$FILE" in
*.tar.gz|*.tgz)
tar -xzvf "$FILE" -C "$DEST"
;;
*.tar.bz2)
tar -xjvf "$FILE" -C "$DEST"
;;
*.tar.xz)
tar -xJvf "$FILE" -C "$DEST"
;;
*.zip)
unzip "$FILE" -d "$DEST"
;;
*.rar)
unrar x "$FILE" "$DEST"
;;
*.gz)
gunzip -c "$FILE" > "$DEST/$(basename ${FILE%.gz})"
;;
*.bz2)
bunzip2 -c "$FILE" > "$DEST/$(basename ${FILE%.bz2})"
;;
*)
echo "不支持的格式: $FILE"
exit 1
;;
esac
if [ $? -eq 0 ]; then
echo "=== 解压完成 ==="
else
echo "!!! 解压失败 !!!"
exit 1
fi
Python脚本(跨平台)
#!/usr/bin/env python3
# compress_tool.py
import os
import sys
import zipfile
import tarfile
import shutil
from pathlib import Path
def compress_zip(source_dir, output_file):
"""压缩为 ZIP 格式"""
with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, source_dir)
zipf.write(file_path, arcname)
print(f"完成: {output_file}")
def compress_tar(source_dir, output_file):
"""压缩为 tar.gz 格式"""
with tarfile.open(output_file, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
print(f"完成: {output_file}")
def extract_file(file_path, output_dir):
"""解压文件"""
os.makedirs(output_dir, exist_ok=True)
if file_path.endswith('.zip'):
with zipfile.ZipFile(file_path, 'r') as zipf:
zipf.extractall(output_dir)
elif file_path.endswith(('.tar.gz', '.tgz')):
with tarfile.open(file_path, 'r:gz') as tar:
tar.extractall(output_dir)
elif file_path.endswith('.tar.bz2'):
with tarfile.open(file_path, 'r:bz2') as tar:
tar.extractall(output_dir)
else:
raise ValueError(f"不支持的格式: {file_path}")
print(f"解压完成到: {output_dir}")
def main():
"""命令行处理"""
if len(sys.argv) < 2:
print("用法:")
print(" 压缩: python compress_tool.py compress <源目录> [输出文件]")
print(" 解压: python compress_tool.py extract <压缩文件> [输出目录]")
return
action = sys.argv[1]
if action == 'compress' and len(sys.argv) >= 3:
source = sys.argv[2]
output = f"{source}.zip" if len(sys.argv) < 4 else sys.argv[3]
if output.endswith('.zip'):
compress_zip(source, output)
elif output.endswith('.tar.gz'):
compress_tar(source, output)
elif action == 'extract' and len(sys.argv) >= 3:
file_path = sys.argv[2]
output_dir = sys.argv[3] if len(sys.argv) > 3 else "extracted"
extract_file(file_path, output_dir)
else:
print("无效的命令")
if __name__ == "__main__":
main()
高级功能脚本
#!/bin/bash
# advanced_backup.sh - 带加密和日志功能
LOG_FILE="backup.log"
# 日志函数
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
# 带密码加密压缩
secure_compress() {
local src="$1"
local dst="$2"
local password="$3"
tar czf - "$src" | openssl enc -aes-256-cbc -salt -pass pass:"$password" -out "$dst.enc"
}
# 带进度显示的压缩
compress_with_progress() {
local src="$1"
local dst="$2"
# 使用进度条
tar -czf "$dst" "$src" &
PID=$!
# 显示进度动画
while kill -0 $PID 2>/dev/null; do
printf "压缩中..."
printf "."
sleep 1
printf "\b\b\b\b\b\b"
done
wait $PID
if [ $? -eq 0 ]; then
log "压缩完成: $dst"
else
log "压缩失败"
fi
}
# 清理旧备份
cleanup_old_backups() {
local dir="$1"
local keep_days=7
find "$dir" -name "backup_*" -mtime +$keep_days -delete
log "已清理 $keep_days 天前的备份"
}
# 主函数
main() {
log "开始备份流程"
# 执行备份
SOURCE_DIR="/var/www/html"
BACKUP_DIR="/backups"
# 创建备份
BACKUP_FILE="${BACKUP_DIR}/website_$(date +%Y%m%d_%H%M%S).tar.gz"
compress_with_progress "$SOURCE_DIR" "$BACKUP_FILE"
# 如果需要加密
# secure_compress "$SOURCE_DIR" "$BACKUP_FILE" "your_password"
# 清理旧备份
cleanup_old_backups "$BACKUP_DIR"
log "备份流程完成"
}
main
Windows批处理脚本
@echo off
REM compress_script.bat
set /p action=选择操作 (compress/extract):
set /p src=输入源路径:
set /p dst=输出路径:
if /i "%action%"=="compress" (
REM 创建压缩
powershell Compress-Archive -Path "%src%" -DestinationPath "%dst%.zip" -Force
echo 压缩完成: %dst%.zip
) else if /i "%action%"=="extract" (
REM 解压文件
powershell Expand-Archive -Path "%src%" -DestinationPath "%dst%" -Force
echo 解压完成: %dst%
) else (
echo 无效操作
)
pause
自动定时备份脚本
#!/bin/bash
# cron_backup.sh - 定时备份
# 配置文件
CONFIG_FILE="/etc/backup.conf"
# 读取配置
if [ -f "$CONFIG_FILE" ]; then
source "$CONFIG_FILE"
else
SOURCE_DIR="/home/user"
BACKUP_DIR="/backup"
LOG_FILE="/var/log/backup.log"
fi
# 备份函数
do_backup() {
date +"%Y-%m-%d %H:%M:%S Backup started" >> "$LOG_FILE"
# 创建备份
BACKUP_NAME="backup_$(date +%Y%m%d).tar.gz"
tar -czf "${BACKUP_DIR}/${BACKUP_NAME}" "$SOURCE_DIR"
# 检查结果
if [ $? -eq 0 ]; then
echo "$(date) Backup successful: ${BACKUP_NAME}" >> "$LOG_FILE"
else
echo "$(date) Backup failed" >> "$LOG_FILE"
exit 1
fi
}
# 清理函数
cleanup_old() {
# 删除7天前的备份
find "$BACKUP_DIR" -name "backup_*" -mtime +7 -exec rm {} \;
}
# 主函数
main() {
do_backup
cleanup_old
echo "$(date) Backup completed" >> "$LOG_FILE"
}
main
使用说明:
- 添加执行权限:
chmod +x script.sh - Shell脚本用法:
./compress.sh或/path/to/script.sh - Python脚本:
python3 compress_tool.py compress /path/dir - 定时任务:添加到crontab:
0 2 * * * /path/to/backup.sh
选择哪种脚本取决于:
- 操作系统(Linux/Windows/Mac)
- 文件类型(zip/tar/rar等)
- 是否需要加密
- 是否需要自动化定时备份
- 是否需要图形界面