Creating a backup script for a Linux server involves scripting and scheduling regular backups to ensure data integrity and recovery options. Below is a simple example of a backup script using the tar
command for creating compressed archives. This script assumes you want to back up specific directories. Customize it according to your server’s directory structure and backup requirements.
Create a new file, for example, backup.sh
, and make it executable:
touch backup.sh
chmod +x backup.sh
Edit the script using a text editor (e.g., nano
or vim
):
nano backup.sh
Add the following content to the script:
# Backup script for Linux server
# Directories to backup
backup_dirs=“/etc /var/www /home/user”
# Backup destination directory
backup_dest=“/path/to/backup”
# Backup file name format (e.g., backup_2023-12-01.tar.gz)
backup_filename=“backup_$(date ‘+%Y-%m-%d’).tar.gz”
# Log file for backup process
log_file=“/var/log/backup.log”
# Create backup
echo “[$(date ‘+%Y-%m-%d %H:%M:%S’)] Starting backup” >> “$log_file“
tar -czvf “$backup_dest/$backup_filename“ $backup_dirs >> “$log_file“ 2>&1
if [ $? -eq 0 ]; then
echo “[$(date ‘+%Y-%m-%d %H:%M:%S’)] Backup completed successfully” >> “$log_file“
else
echo “[$(date ‘+%Y-%m-%d %H:%M:%S’)] Backup failed” >> “$log_file“
fi
Customize the script:
- Modify the
backup_dirs
variable to include the directories you want to back up. - Set the
backup_dest
variable to the directory where you want to store the backup files. - Adjust the
backup_filename
format according to your preferences. - Update the
log_file
variable to the desired location for the log file.
Save the changes and exit the text editor.
To run the backup manually:
./backup.sh
To schedule regular backups, you can use cron jobs. Edit the crontab file:
crontab -e
Add the following line to run the backup script daily at a specific time:
0 2 * * * /path/to/backup.sh
This example runs the script daily at 2:00 AM. Adjust the timing according to your preferences.
Save the changes and exit the crontab editor.
This is a basic backup script, and depending on your server’s complexity, you might need to consider additional factors like databases, system configurations, and permissions. Additionally, for critical systems, consider using dedicated backup tools for more comprehensive solutions.