crop faceless developer working on software code on laptop

How to Create a Shell Script to Backup Files in a Directory

As a system administrator, it is important to regularly backup files and directories of your website, blogs, and company. In this article, we will look at how to create a shell script to backup files in a directory using the tar command.

What are the steps to create a shell script to backup files in a directory?

  1. Create an empty shell script using the following command in the terminal:
$ sudo vi data_backup.sh
  1. Add the following tar command to backup files in a directory /home/data to backup.tar.gz. You can replace the directory path and backup file name below as per your requirement.
$ sudo tar -cvpzf /home/backup.tar.gz /home/data

In the above command,

  • c – compression
  • v – verbose
  • p – retain file permissions
  • z – create gzip file
  • f – regular file
  1. Add the following code to your shell script:
#!/bin/sh
timestamp="$(date +'%b-%d-%y')"
sudo tar -cvpzf /home/backup-${timestamp}.tar.gz /home/data

Save and close the file. In the above code, the first line sets the execution environment, the second line saves timestamp value and the third line does the backup by creating a .tar.gz file. We use the timestamp variable to create a new filename every time the script is run so that the backups remain separate and there is no overwriting.

  1. Run the following command to make your script executable:
$ sudo chmod +x data_backup.sh
  1. Verify the script by running the following command:
$ sudo /home/data_backup.sh
  1. Automate Backup: It is advisable to create a cron job to run the above script regularly in an automatic manner. For this, open crontab with the following command:
$ sudo crontab -e

Add the following line to run the above shell script regularly every day at 10 a.m:

0 10 * * * /home/data_backup.sh

This will run the script every day at 10 a.m. You can modify the time as per your requirement.

How to restore files from a backup in Linux

To restore files from a backup in Linux, you can use the restore command. Here are the steps to restore files from a backup:

  1. Assuming you have a link of the tar archive you want to restore for /var/www.
  2. Run the following command to restore the backup:
tar xvpfz backup.tgz -C /

In the above command, -x is used to extract files from the archive, -v is used to display the progress of the extraction, -p is used to preserve the permissions of the files, -f is used to specify the archive file, -z is used to decompress the archive file, and -C is used to specify the directory where the files should be extracted.

EN