In the last chapter, you learned about how shell interprets any command, which is entered in the terminal or the command line. We also studied command substitution and separators in detail.
In this chapter, we will cover following topics:
Let's learn about creating variables in 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 prefix $ before the variable.
For example:
$ echo person person $ echo $person Ganesh Naik
The unset command can be used to delete a variable:
$ a=20 $ echo $a $ unset a
The unset command will clear or remove the variable from shell environment as well.
$ person="Ganesh Naik" $ echo $person $ set
Here, the
set command will show all variables declared in shell.
$ declare -x variable=value
Here, the declare command with the –x option will make it an environmental or global variable. We will understand more about environmental variables in the next sessions.
$ set
Again here, the set command will display all variables as well as functions that have been declared.
$ env
Here, the env command will display all environmental variables.
variable=value
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 processes, terminal, or shell.
Let's write a Shell script as follows:
#!/bin/bash # This script clears the window, greets the user, # and displays the current date and time. clear # Clear the window echo "SCRIPT BEGINS" echo "Hello $LOGNAME!" # Greet the user echo echo "Today's date and time:" date # Display current date and time echo # Will print empty line my_num=50 my_day="Sunday" echo "The value of my_num is $my_num" echo "The value of my_day is $my_day" echo echo "SCRIPT FINISHED!!" echo

Let's see the effect of $, "", '' and \ on variable behavior:
#!/bin/bash planet="Earth" echo $planet echo "$planet" echo '$planet' echo \$planet echo Enter some text read planet echo '$planet' now equals $planet exit 0
Output:

You will learn about the read command in the next chapters. Using read, we can ask the user to enter data, which can be stored in a variable.
From the preceding script execution, we can observe that $variable and "$ variable" can be used for displaying the content of the variable. But if we use '$variable' or \$variable, then 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 variable content.