Understanding Variables in Bash

March 25, 2021

Let’s learn about creating variables in a shell.

Declaring variables in Linux is very easy. We just need to use the variable name and initialize it with the required content.

$ person="Ganesh Naik"

To get the content of the variable, we need to add the prefix $ before the variable, for example:

$ echo person
$ echo $person
Ganesh Naik

The unset command can be used to delete the declared variable:

$ a=20$ echo $a
$ unset a

The unset command will clear or remove the variable from the shell environment as well.

Here, the set command will show all variables declared in the shell:

$ person="Ganesh Naik"
$ echo $person$ set

Here, using the declare command with the -x option will make it an environmental or global variable. We will find out more about environmental variables in the next section.

$ declare -x variable=value

Here, the env command will display all environmental variables:

$ env

Whenever we declare a variable, that variable will be available in the current Terminal or shell. This variable will not be available to any other Terminal or shell:


Let’s write a shell script, as follows:

# This script clears the window, greets the user, 
# and displays the current date and time. 
clear                                   # Clear the window 
echo "Hello $LOGNAME!"             # Greet the user 
echo "Today's date and time:" 
date                           # Display current date and time 
echo                 # Will print empty line 
echo "The value of my_num is $my_num" 
echo "The value of my_day is $my_day" 

Let’s see the effect of $""'' on variable behavior:

echo $planet 
echo "$planet" 
echo '$planet' 
echo $planet 
exit 0

The output is as follows:



From the preceding script’s execution, we can observe that $variable and "$ variable" can be used to display the content of the variable. But if we use '$variable' or $variable, then the special functionality of the $ symbol is not available. The $ symbol is used as a simple text character instead of utilizing its special functionality of getting the variable’s content.

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur


Submit a Comment

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

11 + eighteen =