Bash Scripting for Automated Backups in DevOps
Bash Scripting for Automated Backups in DevOps
in DevOps
Author: Zayan Ahmed | Estimated Reading time: 4 mins
Imagine you are a DevOps engineer managing a web server. This server hosts important
files, databases, and configurations that should be backed up regularly. If a server crash or
accidental deletion occurs, you could lose all your data. To prevent this, you decide to write a
Bash script that automatically creates backups every day and stores them safely.
# Variables
SOURCE_DIR="/var/www/html" # Directory to back up
BACKUP_DIR="/backup" # Where backups will be stored
DATE=$(date +"%Y-%m-%d") # Current date
BACKUP_FILE="$BACKUP_DIR/backup-$DATE.tar.gz" # Backup filename
Log files accumulate over time and can take up a lot of disk space. To keep storage under
control, you need to archive logs older than 7 days and store them as zip files in a backup
directory.
# Variables
LOG_DIR="/var/log/myapp" # Directory where logs are stored
BACKUP_DIR="/backup/logs" # Directory to store archived logs
DATE=$(date +"%Y-%m-%d") # Current date
Databases store critical information, and losing data could be disastrous. To ensure safety, a
scheduled backup of the database should be performed.
# Variables
DB_NAME="mydatabase" # Database name
DB_USER="dbuser" # Database user
DB_PASSWORD="dbpassword" # Database password
BACKUP_DIR="/backup/db" # Backup directory
DATE=$(date +"%Y-%m-%d") # Current date
BACKUP_FILE="$BACKUP_DIR/db-backup-$DATE.sql.gz"
Local backups are useful, but if the server fails, the backups could also be lost. To ensure
safety, backups should be synced to a remote storage location.
# Variables
LOCAL_BACKUP_DIR="/backup" # Local backup directory
REMOTE_USER="backupuser" # Remote server user
REMOTE_HOST="backupserver.com" # Remote server address
REMOTE_DIR="/remote/backup" # Remote backup directory
To automate these backups, add the following lines to your crontab file:
By using Bash scripting, you can ensure that important data is always backed up without
having to remember to do it manually.
🤔
😊
Want more ?
Follow me on LinkedIn