Backup files and folders using shell script in Linux

Home » Computer » Backup files and folders using shell script in Linux

Backup files and folders using shell script in Linux


In the previous blog we studied how to write a shell script. In this we will backup files and directories in Linux using tar and cron jobs.

Tar allows you to easily and quickly backup your files and folder.
Cron Jobs allow you to schedule your tasks and run automatically.

Backup your files using the tar command.

For eg, I have folder called /mydata in Documents directory and I want to make backup of this folder with all its sub directories at different location in Pictures directory.
The command for the same is

tar – creates the archive.
c – create a new backup archive.
v – verbose mode, tar will print what it’s doing to the screen.
p – preserves the permissions of files put in the archive for restoration later.
z – compress the backup file with ‘gzip’ to make it smaller.
f <filename> – specifies where to store the backup, for eg: backup.tar.gz is the filename.


Now add tar command in bash script to make this whole backup process automatic.
To make this script automatic and run in background we will use cron job
Create file using nano editor and paste below code.

This script will make backup of /mydata directory and save it into a single compressed file in Pictures directory.

In Linux we can automate the process. Using cron jobs is a mush better way to schedule task.
For setting up cron jobs we use crontab -e command in shell, this command is to edit our cron jobs file. If crontab -e command is executed first time it will ask for default text editor, just select editor you want and start editing.

Open crontab editor utility:

It has 6 parts see below explanation:

Minutes – 0 to 59
Hours – 0 to 23
Day of month – 1 to 31
Month – 1 to 12
Day of week – 0 to 6
Command – Shell Command

In above condition my crontab file is like this.

This script will run at 12:00:00 on every Monday.