BASH Bourne Again Shell

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:

# mkdir /backup

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

# vi /backup.sh

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. 

Automation

In Linux, Cron jobs can be used for task scheduling as they are easy to use.

Example

Showing a cron job line with 6 parts:

MinutesHoursDay of MonthMonth Day of WeekCommand
0 to 590 to 231 to 311 to 120 to 6Shell Command

To open crontab editor utility, run:

# crontab -e

Note: You can observe that the edit rules are similar to those of the vi editor.

Example One

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

Example Two

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.

Categories:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *