This article helps you automatically backup files and directories in Linux.
The example can be for any files or directories located on your server and with the correct user privileges.
Archive the content with commands
Use tar to backup your files. It is straightforward. Just use the following command:
tar -cvpzf /backup/backupfilename.tar.gz /data/directory
My example for backing up the HTML folder
tar -cvpzf /backup/myexample.com.tar.gz /var/www/html
It is important to make sure that the destination folder exists, if not, create it using the following command:
Explanation of tar command
- tar = Tape archive
- c = Create
- v = this lists all files that are archived.
- p = used to preserve files and directory permissions.
- z = this tells tar to compress / zip files.
- f = this allows tar to get the file name.
How to backup files with a shell script
To do this, add the tar command in a bash script to make this process automatic. It is also advisable to add a dynamic value in the name to prevent overwriting of backup files.
Create a file using an editor, i.e.
vi backup.sh and paste the script below
Paste the following script and change your details.
#!/bin/bash # This command is used to read the date. TIME='date +%b-%d-%y' # the filename, including the date. FILENAME=backup-example-$TIME.tar.gz # this is the source backup folder. SRCDIR=/var/www/html # Destination of the backup file. DESDIR=/backup tar -cpzf $DESDIR/$FILENAME $SRCDIR
Note: The v parameter for the tar command was not necessary here.
In Linux, Cron jobs can be used for task scheduling as they are easy to use.
Showing a cron job line with 6 parts:
|Minutes||Hours||Day of Month||Month||Day of Week||Command|
|0 to 59||0 to 23||1 to 31||1 to 12||0 to 6||Shell Command|
To open crontab editor utility, run:
Note: You can observe that the edit rules are similar to those of the vi editor.
An example to run a script every day at 03:00:00 type this in the editor.
# M H DOM M DOW CMND
00 03 * * * /bin/bash /backup.sh
To run the same script twice a week on Tuesday and Friday, type the following command in the editor:
# M H DOM M DOW CMND
00 03 * * 2,5 /bin/bash /backup.sh
Note: You can sometimes run out of disk memory if the source folder is too big.