Back Up Your System Using Simple Shell Script
Created May 9, 2020
Updated October 22, 2024
2 min read

Back Up Your System Using a Simple Shell Script

This is a super easy way to back up your system without spending a dime. It can really come in handy, as backup is always important.

Someone said “When your data doesn’t exist three times, it means it doesn’t exist at all.” So make backups and save your backups.

Here we are:

#!/bin/

date

echo "############### Backup of files on my server ###############"

backupfilename=server_backup_`date '+%Y-%m-%d'`

echo "----- Sql first and dumping current DB -----"

rm -f /tmp/backup.sql

mysqldump --user=youruser --password=yourpassword --all-databases --add-drop-table > /tmp/backup.sql

echo "----- Tar plus zip all files -----"

tar cvf /home/mybackups/files/${backupfilename}.tar /home/www/html/* /tmp/backup.sql

gzip /home/mybackups/files/${backupfilename}.tar

chmod 666 /home/mybackups/files/${backupfilename}.tar.gz

echo "############### Backup done successfully.... ###############"

date

***

Now let’s explain each line:

date => we want to see the server date in our log file.

backupfilename=server_backup_`date ‘+%Y-%m-%d’` => backup file name with date

rm -f /tmp/backup.sql ==> we delete the old generated sql backup file

mysqldump => we backup all sql databases again

tar cvf home/www/html/ /tmp/backup.sql => You back up everything home/www/html/* and /tmp/backup.sql You can also exclude certain paths with: –exclude=’yourfilepath’.

Now let’s run the script:

Name your file ‘backup.sh’.

To run it, you need to open the terminal prompt and start with a dot ‘.’. So if you name your file backup.sh, you will get .backup.sh.

Now we’re going to automate it because you probably don’t want to do it manually every day.

So if you want to run it automatically every day at 11:55 p.m., you open your crontab with crontab -e and add this:

55 23 * * * /path/toyourfile/backup.sh >> /path/toyourlogfile/backups.log

And, close your crontab terminal with “:x”

NOTE:

>> /path/toyourlogfile/mybackups.log is not required, it is only necessary if you want to be able to see your backup log in case of an error.

If you want to set a different time in your cron I recommend using this tool which is super easy and will get the job done.

In a Linux environment, I use a Bash backup script to specify the directory I want to archive, copy the files to a backup location, and maintain a reliable backup of my file system.

If you are seeking assistance with custom web development, please contact our web development agency. We have over a decade of experience in web development and we are the best web agency in Montreal.