How to backup directory in Linux (using cron)

Very simple script, for regular backup of a specific directory under Linux.

Create file backup.sh

#!/bin/sh

SOURCE=/path/of/data #what should we backup
DESTINATION=/home/user/backups #where to store backups
DELETEAFTER=5 #how many days should we store the backups

mkdir -p $DESTINATION
cd $DESTINATION
tar -zcvf latest-backup.tgz $SOURCE
mv latest-backup.tgz $(date +%y%m%d%H)-backup.tgz
find . -name '*-backup.tgz' -mtime +$DELETEAFTER -delete

Mark the file as executable:

chmod a+x backup.sh

Now, open the crontab editor:

crontab -e

And add this line (with the correct path to your backup.sh file):

45 3 * * * /home/user/backup.sh

In this case, it will execute every night at 03:45

Leave a Reply

Your email address will not be published. Required fields are marked *