Image for post
Image for post

Linux Backup Script

Fotios Floros
Nov 21, 2016 · 2 min read

This tutorial explains how to create a bash script which can backup the files you need. This backup process will be automatic and it is something that every linux user or admin needs.

In other words, in this tutorial you will learn how to:

  1. Use tar in order to create your backup file

2. Schedule your backup task

Use tar in order to create your backup file

You can use a simple text editor or a command line editor like vi, in order to edit/create your script, let’s name it Remember that .sh is the extension that the bash scripts must have.

The code of your script will be the following:

#!/bin/bash #typically the first line of the bash scriptsBACKUPTIME=`date +%b-%d-%y` #get the current dateDESTINATION=/home/usr/path/backup-$BACKUPTIME.tar.gz #create a backup file using the current date in it's nameSOURCEFOLDER=/home/usr/path/data_folder #the folder that contains the files that we want to backuptar -cpzf $DESTINATION $SOURCEFOLDER #create the backup

The important command here is the following:

tar -cpzf $destination $source

But what about -cpzf parameter?

c: create

v: verbose mode, verbosely list files processed

p: preserve permissions for the new files

z: compress the files in order to reduce the size

f: use archive file or device ARCHIVE

In case you need to look what other options you can use, write the following command

man tar

Schedule your backup task

We are going to use cron, which is a linux daemon that allows us to run scripts in certain scheduled moments. Crontab files automate backups, system maintenance and other useful tasks.

In order to edit the crontab file with the editor you prefer(nano is the easiest), run in a terminal the command

crontab -e

Let’s understand the contrab line format:

minute(0–59) hour(0–23) day(1–31) month(1–12) weekday(0–6) command

Let’s say that we want to run the script everyday at 12:30 a.m. we would type

29 0 * * * /bin/bash /path/

29 stands for the 30 minute

0 stands for 12 a.m.

The first * stands for everyday, the second * stands for every month, the third * stands for every week day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store