List of Contents:
- Introduction
- Declare a Variable
- Print a Variable Using the “Echo” Command
- Print a Variable Using the “Printf” Command
- Local and Global Variables
- Argument Variable of a Bash Function
- Exporting the Variable
- Command-Line Variables
- Use of the $PATH Variable
- Use of the $RANDOM Variable
Introduction
No data type declaration is mandatory for declaring the variables in Bash because Bash is a weakly typed scripting language. However, the “declare” command can be used to declare a variable by mentioning that data type of the variable. Bash variable is declared without any “$” symbol like other scripting languages but the “$” symbol is used in front of the variable name to print the value of the variable. Bash does not support any space before and after the assignment(=) operator when assigning a value to the variable.
1. Special Variables
Bash has some special variables that are used for special purposes. Some of the special variables which are mostly used in the Bash script are described in the following:
Variable | Purpose |
$$ | It is used to print the current process ID. |
$0 | It is used to print the executing script name. |
$1-$5 | It is used to print the first five argument values. |
$@ | It is used to read all arguments that are passed at the executing time of the script. |
$# | It is used to count the total number of arguments. |
$? | It contains the exit status of the current process. |
2. Environment Variables
The environment variables work like the global variable and these variables can be accessed from any shell. The “env” command prints the list of all environment variables of Bash. The purposes of using some useful environment variables are mentioned as follows:
Variable | Purpose |
$LANG | It contains the current character set information. |
$PATH | It contains the stored path value. |
$USER | It contains the name of the user who is executing the script. |
$LOGNAME | It contains the current login user name. |
$HOME | It contains the location of the home directory. |
$RANDOM | It is used to generate a random number. |
Declare a Variable
The following script shows different ways to declare the variables in the Bash script. The “declare” command is used with “-i” option in the script to declare a variable of integer data type. If any string value is assigned to this variable, 0 is assigned to the variable. The first variable named “$Str” contains a string. The second variable named “$n1” contains a number. The third variable named “$n2” also contains a number that is declared by the “declare” command. The “read” command is used in the script to assign an input value that is taken from the user to the fourth variable named “$val”.
Str="Linux"
#Assign a numeric value without the `declare` command
n1=550
#Assign a numeric value with the `declare` command
declare -i n2=340
#Assign value after calculation
((result=n1+n2))
#Assign the value taken from the user to a variable
read -p "Enter a string: " val
#Assign a variable to another variable
n2=$val
The script is executed with the numeric input value of 89 that is numeric. So, the “$n2” variable contains the value of 89.
The script is executed with the string input value of “test” that is a string. So, the “$n2” variable contains the value of 0 because “$n2” was declared with integer data type.
Print a Variable Using the “Echo” Command
“Echo” is one of the commands that can be used to print the output in the terminal. In the following script, the course value is taken as input from the user and the input value is printed with another string using the “echo” command. It is necessary to use the double quotes(“) with the “echo” command to print the value of the variable. Otherwise, the name of the variable is printed.
#Assign the value taken from the user
read -p "Enter the course name: " course
#Print the value of the variable by using `echo`
echo "The course name is $course"
The following output appears after executing the script with the “CSE-407” value:
Print a Variable Using the “Printf” Command
“Printf” is another Bash command to print the formatted output in the terminal. In the following script, two string values are assigned to the variables. Then, the “printf” command is used to print the values of the variables with the “%s” specifier. Two “%s” specifiers are used in the script to print the values of the two variables.
#Assign two string values
course_code="CSE406"
course_teacher="Alex"
#Print the variables by using the `printf`
printf "%s course is taken by %s\n" $course_code $course_teacher
The following output appears after executing the script. The values of the variables are printed with the other string values based on the position of the “%s” specifier:
Local and Global Variables
The variables which are declared outside the function are called “global” variables and the variables which are declared inside the function are called “local” variables. The “local” keyword is used to define the local variables. The uses of global and local variables are shown in the following script. In the script, 87 is assigned in the “$num” global variable and 25 is assigned in the “$num” local variable.
#Assign a global variable
num=87
function func {
#Print the global variable
echo "The value of the global variable is $num"
#Define a local variable with the same name
local num=25
#Print the local variable
echo "The value of the local variable is $num"
}
#Call the function
func
#Print the global variable again
echo "The value of the global variable after calling the function is $num"
The following output appears after executing the script. According to the output, the global variable remains unchanged after executing the function and the value of the global variable is 87 before and after calling the function.
Argument Variable of the Bash Function
The method of passing the argument values to the Bash functions is not the same as in the other programming languages. The function argument values are passed with the space when the function is called. The “$1”, “$2”, .., and “$n” variables are used inside the function to read the argument values. The method of using three function arguments is shown in the following script. In the following script, three string values are passed into the function named book_names() which are read by the “$1”, “$2”, and “$3” variables. These argument values are printed with formatting by the “printf” command.
book_names()
{
#Read the argument values
book1=$1
book2=$2
book3=$3
echo "Book names are:"
#Print the argument values
printf "1. %s\n2. %s\n3. %s\n" "$book1" "$book2" "$book3"
}
#Call the function with 3 arguments
book_names "Bash Pocket Reference" "Learning the Bash Shell" "Bash CookBook"
The following output appears after executing the script. The serial number and the new line are added to the output:
Exporting the Variable
Sometimes, it requires sharing the value of the variable in multiple shells. The “export” command is used to do this task. The method of using the “export” command is shown in this part of the tutorial.
Run the following commands to check how the variable resets after executing the “bash” command. Here, a string value is set to the “$OS” variable and is printed later in the terminal. Then, when the “$OS” variable is printed again after executing the “bash” command, nothing will be printed because all shell variables are reset after executing the “bash” command.
$ echo $OS
$ bash
$ echo $OS
The following output shows that the value of the “$OS” variable is empty after executing the “bash” command:
If you want to share the value of the particular shell variable in a different shell, you have to use the “export” command before executing the “bash” command. Run the following commands to export the value of the “$OS” variable and print the value after executing the “bash” command. Here, the “$OS” variable is exported before printing the variable and executing the “bash” command. Then, the “$OS” variable is printed again.
$ export OS
$ echo $OS
$ bash
$ echo $OS
The following output shows that the value of the “$OS” variable contains the previous value after executing the “bash” command:
The exported variable is used in the following script to check whether the variable contains the previous value or not:
#Print the exported variable
echo "The operating system is $OS"
The following output shows that the exported “$OS” variable contains the previous value which was CentOS:
Command-Line Variables
The command-line arguments are used to pass the values to the script at the time of executing the script. The uses of “$#”, “$0”, and “$1” variables are shown in the following script. The total number of command-line arguments is counted by the “$#” variable and is stored in the “$total” variable. If the value of the “$total” is more than 0, the executing script filename is printed using the “$0” variable and the first argument value is printed using the “$1” variable. If no argument is passed at the time of executing the script, an error message is printed.
#Count the total number of arguments
total=$#
if [ $total -ne 0 ]
then
#Print the total number of arguments
echo "Total command line arguments are $total"
#Print the script name
echo "The script name is $0"
#Print the first argument
echo "The first argument value is $1"
else
#Print message
echo "No argument value is given."
fi
The following output appears after passing an argument value at the time of executing the script:
The following output appears after executing the script without any argument:
Use of $PATH Variable
The “$PATH” is one of the important environment variables of Bash. The locations of the different executable files and script files are stored in this variable. When the user tries to access any executable file or the script file, the shell checks the location of that file in the “$PATH” variable. The value of this variable can be changed based on the requirements.
Run the following command to check the current output of the “$PATH” variable:
Suppose you want to add the “/home/fahmida/tempdir” location in the “$PATH” variable. Run the following commands to add the new location in the “$PATH” and the current value of the “$PATH” variable again:
$ echo $PATH
The following output appears after executing the commands. The new location is added at the end of the “$PATH” variable:
Use of $RANDOM Variable
Bash has no random function to generate the random numbers like other programming languages. The special variable which is “$RANDOM” can be used to generate the numbers in Bash. The following script generates five random numbers by iterating the “for” loop five times. The length of each random number may vary in each iteration of the loop.
echo "Generated 5 random numbers:"
#Iterate the loop for 5 times
for i in {1..5}
do
#Print the random numbers
echo $RANDOM
done
The following similar output appears after executing the script. According to the output, three numbers of 5 digits and two numbers of 3 digits are generated. The output will be changed if you execute the script again:
Conclusion
The methods of using the different types of Bash variables effectively are explained in this tutorial using multiple Bash commands and scripts. The Bash users will get a clear knowledge about the uses of different Bash variables after reading this tutorial.