Variables in Linux Shell Scripts: Explained With Examples

Sarath Pillai's picture
Bash Shell Variables

A computer should be able to store information and then later on do operations on that information. There should be a way to store information and then later on retrieve that information. Computer programs also deal with information storage and retrieval. To store information we need storage space(computer memory). In order to retrieve the information stored in memory, we need to specify the storage location where the information is stored.

 

So basically we need a name, or some sort of identifier to retrieve the stored information. This is where variables comes into picture. In this article, we will be discussing about variables in bash shell scripting.

 

This article is part of the tutorial series about "bash shell scripting". If you are a beginner, I would then recommend reading the below two articles before proceeding further with this one.

 

Read: An Introduction To Bash Shell Scripting

Read: Methods to Execute A Shell Script in Linux

 

So variable is something using which you can store information(data), and then later on retrieve it or do operations on it. Without variables, its pretty much impossible to write a useful program. Without variables you cannot grab information from the user, you can't do operations on data, you cant loop or count data, you cant change the behavior of a program depending upon some type of data.

Your program will be lame without variables. Any arbitrary data can be stored in a variable(which is nothing but a chunk of memory with a name to access it later).

 

Although a variable uses a chunk of memory to store your data. As far as bash shell is concerned, unlike some other programming languages, you do not need to allocate the memory required by the variable yourself. You also do not need to worry about freeing up the memory after use of the variable.

 

You can define a variable, and write data to it by using the variable name on the left hand side followed by equal to symbol, and the value of the variable on the right hand side as shown in the examples below.

 

Example 1:

variable=value

Example 2:

name=sarath

Example 3:

age=28

 

One important thing to note about variable assignment is the fact that space character is not allowed before and after = symbol. So basically variable = value is invalid. However variable=value is valid variable assignment.

This is because variable = value is exactly same as any other command with parameters. For example, ls -la is very much similar to variable = value. "=" will be considered as the first argument to the command "variable".

variable =value also wont work. This is because =value is again considered as parameter to the command variable.

 

Ok. So Now I Know How To Define A Variable in Bash, And Assign a Value to It. But How do I Access the Variable or Retrieve it later?

 

Well that's quite simple. You can access or retrieve the data inside the variable using the dollar sign($) followed by the variable name as shown in the below example.

 

[root@www ~]#echo $variable
value
[root@www ~]#echo $name
sarath
[root@www ~]#echo $age
28

 

How to interactively set a variable in bash shell, from a user input?

 

You can achieve that very easily using a command called read. An example is shown below.

#!/bin/bash
echo "what is your name?"
read name
echo "Hello $name!. Welcome to Slashroot Scripting Tutorial"

 

 

Executing the above script will first print "what is your name?", and then wait for the user to provide an input. This is because of the second line of the script read name.

The content typed in by the user is then recorded to the variable called name. Which is then printed out to the screen in the next line as shown below.

 

what is your name?
sarath
Hello sarath!. Welcome to Slashroot Scripting Tutorial

 

In the above example, I entered sarath when prompted. Hence the output.

 

 

How to assign the output of a command as value to a variable in bash?

Well that is one of the common use case of variable as far as scripting is concerned. You need to grab the output of a command, and pass that output as a value to the variable. This is quite simple. See the example below.

 

#!/bin/bash
DATE=`date`
echo "Today is $DATE"

 

Its simple and pretty straight forward. Simply put the command inside back quotes as shown in the above example.

date command is a standard Linux command that prints out current date and time. The output of that command is assigned to a variable named DATE, which is then printed out to the screen.

 

How to pass parameters to your script in bash, and assign those parameters as values to variables?

This is also quite simple. Bash provides an out of the box solution for this, which will do the trick for most of your use cases. See the below example.

 

#!/bin/bash
firstname=$1
lastname=$2
scriptname=$0
echo "Hello!. So your Firstname is $firstname, and your Lastname is $lastname and the script that you are executing is $scriptname"

 

Its always like this. $0 indicates the script itself. $1 indicates the first parameter that you pass to the script. $2 the second parameter that you pass. $3 the third, and $4 the fourth and so on...

So why do you need those firstname,lastname and scriptname variables in there. Well you do not need them. The script can be a simple one liner script as shown below.

 

#!/bin/bash
echo "Hello!. So your Firstname is $1, and your Lastname is $2 and the script that you are executing is $0"

 

 

You can execute the script as below.

 

root@localhost:~# ./test1.sh Sarath Pillai
Hello!. So your Firstname is Sarath, and your Lastname is Pillai and the script that you are executing is ./test1.sh

 

If you see the above execution. Space character is what is letting the script know about the parameters(there is space between the first and the second parameter). So how to pass a parameter with space charecter in the parameter itself?

You can do that using quotes as shown below.

 

root@localhost:~# ./test1.sh 'S a r a t h' 'P i l l a i'
Hello!. So your Firstname is S a r a t h, and your Lastname is P i l l a i and the script that you are executing is ./test1.sh

 

How to verify if a command inside the shell script was successful?

Similar to $0, $1 etc, shell provides a built in mechanism for this as well. You can access the exit status of a command using a predefined variable. This variable will contain numerical values which will indicate whether the command was successful or failure.

 

Each and every command in shell returns a numerical return code after execution. This numerical value ranges from 0 to 255.

Shell will set the return code of the last command executed inside a variable called $?. Yes. Its called $?. Almost all command will return the code of zero(0), if it was successful.

 

root@localhost:/opt# ls
testdirectory
root@localhost:/opt# echo $?
0
root@localhost:/opt# ls )
-bash: syntax error near unexpected token `)'
ubuntu@ip-10-12-4-160:/opt$ echo $?
2

 

 

In the above example, the first ls command was successful and hence the exit code was zero. The second ls command was fired with a wrong parameter. Hence the exit code was two(all non zero exit codes generally indicates failures.)

 

How to Unset a variable in bash?

That can be done using unset command as shown below.

 

#!/bin/bash
variable=2
echo The variable value is $variable
unset variable
echo The variable value is $variable

 

The output of the above script is shown below.

 

root@localhost:~# bash test2.sh
The variable value is 2
The variable value is

 

The second echo wont show any value for the variable, because we have removed its value using unset command in the very previous line.

 

 

Rate this article: 
No votes yet

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.