Bash Script – Working of Bash Variables
Last Updated :
31 Jul, 2023
A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a reusability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands one or more times as per our requirements. In programming, a variable is a value that can change, depending on conditions or on information passed to the program. A variable in bash can contain a number, a character, or a string of characters. Here in this article, we are going to discuss the working of variables within Bash Scripting.
Rules for defining variables in Bash Scripts are as follows –
- Variable names can contain uppercase, lowercase letters, numbers, underscores, and digits.
- It is a good practice to use uppercase letters for variable names within Bash scripts.
- Space is not allowed.
- Pre-defined keywords cannot be used. Like if, else, etc.
The simplest example of the use of variables in Bash scripting can be given as –
Example Script:
NAME="Satyajit Ghosh"
echo "His name is $NAME"
Output:
His name is Satyajit Ghosh
The above example shows a variable ‘name‘. Then it is used with an echo command to display its value. So, the basic syntax for writing variables within a Bash Script will be –
Syntax of Writing Variables:
VariableName=value
echo $VariableName #for accessing the value
If we want to change the value of a variable then we can do that. The basic syntax for that will be –
VariableName=value
VariableName=newValue
echo $VariableName #for accessing the value
Below is an example of the same –
Example Script:
AGE=10 #assigning a value
AGE=20 #changing the value
echo $AGE #display the value
Output:
20
Below is the terminal shell depiction after executing the script –
Variable Scope
The scope in a program or script is a region where the variables have their existence. If a variable is declared inside a function then it is generally a local variable and if it is declared outside then it is a global variable. In the case of a bash script, this concept is a little bit different, here any variable whether it is written inside a function or outside a function by default is a global variable. If we want to make a local variable then we need to use the keyword “local”.
An example of the same is given below –
Example Script:
#!/bin/bash
var1="Apple" # global variable
myfun(){
local var2="Banana" #local variable
var3="Cherry" #global variable
echo "The name of first fruit is $var1"
echo "The name of second fruit is $var2"
}
myfun
echo "The name of first fruit is $var1"
# trying to access local variable
echo "The name of second fruit is $var2"
echo "The name of third fruit is $var3"
Output of Variable Scope:
The name of first fruit is Apple
The name of second fruit is Banana
The name of first fruit is Apple
The name of second fruit is
The name of third fruit is Cherry
Here in this above example, var2 is a local variable, so when we are accessing it from the function it is doing fine but when we are trying to access it outside the function, it is giving us an empty result in the output.
On the other hand, unlike programming languages, even though var3 is defined inside a function still it is acting as a global variable and it can be accessed outside the function. Below is the terminal shell depiction after executing the script –
Operations on Variables
We can perform both numerical and string operations on variables on Bash scripting. An example of the same is given below –
Example Script:
NUM1=10 #variable 1
NUM2=5 #variable 2
# Numerical Operations over the variables
SUM=$(( $NUM1 + $NUM2 ))
SUBTRACT=$(( $NUM1 - $NUM2 ))
MULTIPLY=$(( $NUM1 * $NUM2 ))
DIVIDE=$(( $NUM1 / $NUM2 ))
echo "Addition : $SUM"
echo "Subtraction : $SUBTRACT"
echo "Multiply : $MULTIPLY"
echo "Divide : $DIVIDE"
# String Operations over the variables
NAME="GeeksforGeeks"
echo ${NAME:0:5} #substring extraction
FIRST_NAME="Isaac"
LAST_NAME="Newton"
echo ${FIRST_NAME}" "${LAST_NAME}
Output of Operations on Variables:
Addition : 15
Subtraction : 5
Multiply : 50
Divide : 2
Geeks
Isaac Newton
In the above example, we have performed different numerical operations like addition, subtraction, multiplication, and division using variables and also performed basic string operations like concatenation and substring extraction. Below is the terminal shell depiction after executing the script –
Special Variables
There are some special types of variables present in the brush. These are also called internal variables or preset variables. Below is the list of some of them.
$# |
How many command line parameters were passed to the script. |
$@ |
All the command line parameters are passed to the script. |
$? |
The exit status of the last process to run. |
$$ |
The Process ID (PID) of the current script. |
$USER |
The username of the user executing the script. |
$HOSTNAME |
The hostname of the computer running the script. |
$SECONDS |
The number of seconds the script has been running for. |
$RANDOM |
Returns a random number. |
$LINENO |
Returns the current line number of the script. |
Example Script:
function Printname(){
echo "First Name : ${1}"
echo "Last Name : ${2}"
echo "Full name is : $@"
}
Printname Satyajit Ghosh
echo "The name of the user : $USER"
echo "The hostname of the computer : $HOSTNAME"
echo "One random number is $RANDOM"
echo "The process ID of this script : $$"
Output of Special Variables:
First Name : Satyajit
Last Name : Ghosh
Full name is : Satyajit Ghosh
The name of the user : satyajit
The hostname of the computer : satyajit-ThinkPad
One random number is 3239
The process ID of this script : 4301
Below is the terminal shell depiction after executing the script –
Command-line Arguments
We can supply arguments during the execution of the script and those variables can control the behavior of the script. Suppose we have a script as follows –
Example Script:
echo “The First name is $1 and Last name is $2”
Now, if we execute it like this:
./scriptname.sh arg1 arg2
We will see the following output –
Output of Command-line Arguments:
The First name is Satyajit and Last name is Ghosh
Below is the terminal shell depiction after executing the script –
Command Substitution
Command substitution allows us to take the output of a command or program and save it as the value of a variable. Below is the example for the same –
Example Script:
var=$( ls /usr | wc -l )
echo Total $var entries on usr directory
Output of Command Substitution:
Total 13 entries on usr directory
In the above example, we have stored the result of ls /usr | wc -l , in a variable.
Below is the terminal shell depiction after executing the script –
Exporting Variables
Variables are limited to the process they were created in. If we want the variable to be available to another script then we need to export the variable. Below is an example of the same –
Example Script:
First, we will save two files gfg_one.sh and gfg_two.sh, then we will provide the execute permission and have the below codes within them –
gfg_one.sh code:
NUM1=10
echo "gfg_one : The initial value is $NUM1"
export NUM1
./gfg_two.sh
echo "gfg_one : The new value is $NUM1"
gfg_two.sh code:
echo "gfg_two : The initial value is $NUM1"
NUM1=20
echo "gfg_two : The new value is $NUM1"
Output of Exporting Variables:
gfg_one : The initial value is 10
gfg_two : The initial value is 10
gfg_two : The new value is 20
gfg_one : The new value is 10
So here in this example, we have exported the NUM1 variable from gfg_one.sh and called gfg_two.sh script.
gfg_two.sh receives the NUM1 variable and displayed its value as well (line 2 of output).
Now, we can notice one problem in this output in line 4 of the output the value is assumed to be 20 but it is not. Because a copy of the original variable passed to the second script and not the actual one, any change of value in that, will not reflect in the original variable. Below is the terminal shell depiction after executing the script –

Similar Reads
Bash Scripting - Working of Bash Scripting
Bash Scripting is a crucial component of Linux's process automation. You can write a series of commands in a file and then execute them using scripting. A Bash script is a plain text file with a set of commands inside of it. These commands are a combination of ones we typically type on the command l
6 min read
Bash Scripting - Working of Alias
BASH Alias is a shortcut to run commands using some mapping. It is a way to create some shortcut commands for repetitive and multiple tasks. We create an alias in a BASH environment in specified files. We can also incorporate BASH functions, variables, etc to make the Alias more programmatic and fle
7 min read
Batch Script - Working with Environment Variables
Environment Variables refer to the variables which are globally declared and can be accessed by the processor under the management of OS like Windows, Mac, and Linux. In starting they were meant to store the path locations but now they also work with Batch Script. The data of batch programs like inp
2 min read
Batch Script - Local VS Global Variables
In this article, we will see the differences between local and global variables in bash scripting. Variable: The name given to a memory location that is used to store values in a program is called variables. It stores information that can be called and manipulated wherever needed in the program. Sco
4 min read
Bash Script - Define Bash Variables and its types
Variables are an important aspect of any programming language. Without variables, you will not be able to store any required data. With the help of variables, data is stored at a particular memory address and then it can be accessed as well as modified when required. In other words, variables let yo
12 min read
Batch Script - Environment Variables
Environment variables are a collection of dynamic named values that are saved on the system and utilized by programs that are running in shells or subshells on Linux and Unix-based systems. An environment variable is, to put it simply, a variable with a name and a corresponding value. You can alter
6 min read
Scope of a variable
Scope of a variable defines the part of code where the variable can be accessed or modified. It helps in organizing code by limiting where variables are available, preventing unintended changes or conflicts. Understanding scope is key to writing clear, efficient, and maintainable programs. In this a
8 min read
Set - $VARIABLE" in bash
In the world of bash scripting, you may come across the phrase "set - $VARIABLE". But what does it mean? At its most basic, "set - $VARIABLE" is used to split the value of a bash variable into separate words, using the Internal Field Separator (IFS) as the delimiter. For example, if VARIABLE has the
3 min read
Bash Scripting - How to check If variable is Set
In BASH, we have the ability to check if a variable is set or not. We can use a couple of arguments in the conditional statements to check whether the variable has a value. Â In this article, we will see how to check if the variable has a set/empty value using certain options like -z, -v, and -n. Usi
10 min read
Bash Scripting - String
Bash String is a data type similar to integer or boolean. It is generally used to represent text. It is a string of characters that may also contain numbers enclosed within double or single quotes. Example: "geeksforgeeks", "Geeks for Geeks" or "23690" are strings Creating a String A basic declarati
2 min read