Comment
Author: Admin | 2025-04-28
Create a variable at the beginning with the destination folder path and use it for each line. I’ll also do the same for the “cp” command, so if you decide to swap it to use rsync or another command, you’ll have only to edit one line.Here’s a better script:#!/bin/bashDEST_FOLDER='/home/pat/backups/'BACKUP_CMD='/bin/cp'$BACKUP_CMD /etc/app1/file1.conf $DEST_FOLDER$BACKUP_CMD /etc/app2 $DEST_FOLDER -rThe result will be the same, but it will be easier to update. If you want to use a different destination, you just have to update the variable at the beginning.Compress FilesMost of the time, we use compression for backup or at least archive files.I’ll use tar to archive all files in one file and gzip to compress it.Here’s the new and improved script:#!/bin/bashDEST_FOLDER='/home/pat/backups/'DEST_FILE='backup.tar'BACKUP_CMD='/bin/tar -rvf'/bin/rm $DEST_FOLDER/$DEST_FILE.gz$BACKUP_CMD $DEST_FOLDER/$DEST_FILE /etc/app1/file1.conf $BACKUP_CMD $DEST_FOLDER/$DEST_FILE /etc/app2/bin/gzip $DEST_FOLDER/$DEST_FILEI add a new variable DEST_FILE to store the file name of the backup.“tar -rvf” allows you to append several files to one tar file.“gzip” allows you to compress the whole tar file.Stop Overwriting FilesAs you can see from our script, we delete the previous backup each time. That’s not a good thing to do. If there is an issue with the backup, you won’t be able to retrieve an older version.A good practice is to name the backup file with the current date and time. For example:#!/bin/bashDEST_FOLDER='/home/pat/backups/'DEST_FILE="backup-$(date +'%F_%R').tar"BACKUP_CMD='/bin/tar -rvf'$BACKUP_CMD $DEST_FOLDER/$DEST_FILE /etc/app1/file1.conf $BACKUP_CMD $DEST_FOLDER/$DEST_FILE /etc/app2/bin/gzip $DEST_FOLDER/$DEST_FILENothing changed except we add the date in the DEST_FILE variable, so that we stop deleting the previous backup.Each time the script runs, it will now create a new file and keep all the previous versions.Schedule BackupsOnce we have created our script following the steps above, most of the work is done. But it would be more convenient if the backup script ran regularly on its own.Schedule the backup script so that it runs every day automatically.For that, we will use the crontab:Open the user’s crontab:crontab -e Paste this line at the end of the file: 0 0 * * * /usr/local/bin/backup.sh This cron will run your backup script each day at midnight, but you can change it if you want.Save and quit (CTRL+O, Enter, CTRL+X)If you back up files with
Add Comment