Linux and Networking

Linux and Networking

4.3. Variables in bash

A variable is a container where information can be stored. The variables are stored in memory and can be used in shell scripts to save the name of the user who executed it, the current date, the name of a directory, etc.

 

Let’s look at an example of a variable in a shell script:

 

#!/bin/bash

DATE=`date +%d-%m-%y`

echo $DATE

 

In the DATE variable I store the result of executing the command date +%d-%m-%y. For this I use the accent symbol «`» at the beginning and at the end of the command to delimit it. To create this symbol press the accent key and give it a blank space. That’s how that symbol appears.

 

Have you noticed?

That when I assign a value to the variable I do not put the $ symbol in front of it and when I use it I do.

 

When I run this script in my terminal I get the following:

 

$ ./script.sh

03-21-14

 

We can use scripts to store more information such as:

 

USER=user

 

In this case in the USER variable we will store the word user.

 

Let’s look at a more complete example in which a backup of the home directory of a specific user is made:

 

#!/bin/bash

DATE=`date +%d-%m-%y`

USER=user

echo ‘Starting backup…’

tar cvzf /tmp/$USER-$DATE.tgz /home/user

echo ‘Backup finished’

 

As you can see in the DATE and USER variables we are going to save information that will later be used in the tar command to perform the backup.

 

Remember.

In shell script you have to be careful with upper and lower case. DATE and date are different shell script variables. For example, get used to writing variables in capital letters and you won’t have problems.

 

Proposed exercise.

Modify the previous example so that it backups a test directory that you create for this purpose. Try backing up the directory, deleting it, and restoring it to check that your script is working correctly.

The Demeter Project