需求:编写Shell脚本实现指定目录tar.gz压缩并按日期命名复制
Got it, let's build a reliable shell script that handles your full backup and timestamped compression needs perfectly. Here's a complete solution tailored to your requirements:
Shell Script for Timestamped Full Backup
First, here's the full script you can use. Save it as something like ndb_backup.sh and make it executable with chmod +x ndb_backup.sh:
#!/bin/bash # Define source and target directories SOURCE_DIR="/hana/shared/backup_service/backups/30015/NDB/" TARGET_DIR="/hana/data/" # Create target directory if it doesn't exist mkdir -p "$TARGET_DIR" # Generate timestamp in YYYYMMDDHHMMSS format TIMESTAMP=$(date +%Y%m%d%H%M%S) TAR_FILE="${TARGET_DIR}bck_${TIMESTAMP}.tar.gz" # Perform full backup and compression echo "Starting full backup of $SOURCE_DIR to $TAR_FILE..." if tar -czf "$TAR_FILE" -C "$SOURCE_DIR" .; then echo "Backup completed successfully! File saved to: $TAR_FILE" else echo "ERROR: Backup failed!" >&2 exit 1 fi
Let's break down what each part does:
- Directory Definitions:
SOURCE_DIRpoints to the folder you want to back up (note the trailing/to ensure we capture all contents inside, not the folder itself).TARGET_DIRis where the compressed backup will live. - Target Directory Check:
mkdir -pensures the target directory exists—if it doesn't, it creates it (and any parent folders needed) without throwing errors. - Timestamp Generation:
date +%Y%m%d%H%M%Screates a unique timestamp (year, month, day, hour, minute, second) so every backup has a distinct filename, just like your examples (bck_20180121000002). - Tar Command:
-czf: Creates (c) a gzip-compressed (z) archive and specifies the output file (f).-C "$SOURCE_DIR" .: Changes to the source directory first, then archives everything in it (.), which ensures we get all contents of the NDB folder without including the folder itself in the archive.
- Error Handling: The
ifstatement checks if the tar command succeeded. If it did, it prints a success message; if not, it outputs an error and exits with a non-zero code (useful for monitoring or cron jobs).
Extra Tips for Production Use:
- Permissions: Make sure the user running this script has read access to
$SOURCE_DIRand write access to$TARGET_DIR. - Cron Job: To automate backups, add this script to your crontab. For example, to run it daily at midnight, add:
This also logs all output to a log file for debugging.0 0 * * * /path/to/ndb_backup.sh >> /var/log/ndb_backup.log 2>&1 - Clean Up Old Backups: If you don't need to keep backups forever, add a line to delete backups older than X days. For example, to delete backups older than 30 days:
find "$TARGET_DIR" -name "bck_*.tar.gz" -mtime +30 -delete
内容的提问来源于stack exchange,提问作者Momar
相关产品推荐
相关产品推荐

