Automation Scripts using Bash
Shell script to take backup of var/logfile. Run a cronjob to take backup every monday
Here’s a shell script that takes a backup of /var/logfile
, and instructions to set up a cron job to run it every Monday.
Backup Script
Create the Shell Script: Save the following script as
backup_
logfile.sh
:#!/bin/bash # Define the log file and backup directory LOG_FILE="/var/logfile" BACKUP_DIR="/var/logfile_backup" # Ensure the backup directory exists mkdir -p "$BACKUP_DIR" # Create a timestamp for the backup file TIMESTAMP=$(date +'%Y-%m-%d') BACKUP_FILE="$BACKUP_DIR/logfile_backup_$TIMESTAMP.tar.gz" # Create a compressed backup of the log file tar -czf "$BACKUP_FILE" "$LOG_FILE" # Output status if [ $? -eq 0 ]; then echo "Backup created successfully at $BACKUP_FILE" else echo "Backup failed" fi
Using
[ $? -eq 0 ]
is a way to check if the previous command was successful. In this context:This checks if
tar -czf "$BACKUP_FILE" "$LOG_FILE"
ran without errors ($? -eq 0
).If true, it confirms success by outputting "Backup created successfully."
If false (meaning a non-zero exit status), it outputs "Backup failed."
This is helpful for providing feedback on whether the backup was created successfully.
Make the Script Executable:
chmod +x backup_logfile.sh
Setting Up the Cron Job
To run this script every Monday:
Open the crontab editor:
crontab -e
Add the following line to schedule the script to run every Monday at 12:00 AM:
0 0 * * 1 /path/to/backup_logfile.sh
Replace
/path/to/backup_
logfile.sh
with the actual path of your script.
This cron job will execute the backup_
logfile.sh
script every Monday, creating a new backup with the current date.
Backup S3 Bucket Script
Copies an S3 bucket to a local directory.
#!/bin/bash
BUCKET_NAME="my-s3-bucket"
LOCAL_DIR="/backup/s3"
aws s3 sync s3://$BUCKET_NAME $LOCAL_DIR
echo "Backup of $BUCKET_NAME completed in $LOCAL_DIR."