A Simple Backup Shell Script
This article contains a simple shell script which on execution will back up your linux system. If you are not familiar with Backup or Restore, I highly recommend you go through our previous stones on Backup your Linux System, Restore your Backups and Tips on Backup and Restore. Since, the entire posts on Backup was based on GNU tar, the following script will be using tar utility to backup.
You might be wondering why to through such a script when I can simply do it with a single command. The reason for doing so is to show you the power of shell script where a simple script can be used with cron utility to automate your backup whenever you want. So, all you have to do is open an editor ( ed, nano, vi or gedit ), copy the following script and save it to backup.sh ( or anything that you prefer )
#!/bin/sh backup_source=“/home /var/www/ /etc /root /boot /opt” backup_dest=“/mnt/myUSB” date=`date '+%d-%B-%Y'` hostname=$(hostname -s) filename="$hostname-$date.tgz" echo “Backing Up your Linux System” tar cvpzf $backup_dest/$filename $backup_source echo “Backup finished”
How do I execute it ?
Open the terminal and type
sudo bash backup.sh
I have used 5 variables : $backup_source, $backup_dest, $date, $hostname, $filename.
However, you can modify the value of the variables as per your requirement.
$backup_source can be simply your home folder ( $backup_source=“/home” ) , $backup_dest can have other path as well. ( $backup_dest=“/media/backup” ).
Similarly, you can use other options of tar as well.
To list all files in the archive file after backup you can use:
tar tvf $filename
What more … ?
Now, we automate the script execution using cron utility. The cron utility allows the execution of scripts, or commands, at a specified time and date.
Open a terminal and type
sudo crontab -e
Select your preferred editor, and type the following after this line
# m h dom mon dow command 0 6 * * 1 bash /usr/local/bin/backup.sh
The backup.sh script will now be executed at 6:00 am every week.
Here, /usr/local/bin/backup.sh is the path of backup.sh file. You can change the script path appropriately.The -e option enable you to edit the user’s crontab. Similarly you can edit user’s crontab using -u option.
sudo crontab -u rabi -e
1 Comment + Add Comment
Leave a comment
- 40 Basic Linux Command-line Tips and Tricks
- Tips and Tricks for Facebook Chat (Save History/ Video Chat/ Send Files)
- 40 Linux Shell Commands for Beginners
- Creating a Simple GUI for Absolute Beginners (Java Tutorials)
- Online Coding Zones for Programmers
- Special: Facebook Smiley, Special Text Symbols and ASCII Arts
- The First on the World Wide Web