We often need to do things that may put us at risk of losing data in Linux, nevertheless, it’s always better to take systematic backups from time to time.
Today we will be learning about how to use the powerful tool called
tar in Linux to help in the backup process.
Let’s take a quick look at the tar command and the flags that we will be using with it.
Now let’s understand these flags.
- z : Compress the backup file with ‘gzip’ to make it a small size.
- c : Create a new backup archive.
- v : verbosely list files that are processed.
- p : Preserves the permissions of the files put in the archive for later restoration.
- f : use archive file or device ARCHIVE.
Let us now backup the home directory, in my case, the user name is
This will produce the output (for the /backup directory) as
If you wish to exclude some directory to be archived, you can use
--exclude flag, something like this
This will archive everything excluding the
test-folder inside Documents.
And that’s it, this will help you create a backup and store it with the date inside
Doing this once is fine, but what if there was a way to regularly backup your content and automatically wipe out the old backups, wouldn’t that be great. So let’s just do that.
We will use a shell script and cron job to automate this task for us.
First, let’s move into a better directory where we will store our script.
Now copy the mentioned script, it is pretty straightforward. We use
tar to compress and create a backup file under the
$BACKUP_DIR and use
find command to delete old backups.
Set executable permissions for this file.
Now your script is ready to be used.
The final step is to set up the cron job to run this script automatically. We will enter into crontab using
Inside it paste the following lines at the bottom.
This will run this script every Friday at 12:00. To learn more about how to configure these values, I would highly recommend using crontab.guru ↗️.
Hope you found this helpful, see you in the next one.