Shell Scripting - Shell Variables
A shell variable is a small container in memory that holds a value (a string, a number, a filename, etc.). Using variables is the most fundamental part of shell scripting.
You need variables to make your scripts powerful and flexible. You will use them to:
- Store temporary data (e.g., GREETING="Hello").
- Get and hold input from a user (e.g., read USER_NAME).
- Store the output of a command (e.g., TODAY=$(date)).
- Control logic in loops and if statements.
Understanding Variable Types
There are three main types of variables you will encounter.
1. Local Variables
- Scope: Only visible within the current script or shell session.
- Example: my_var="Hello"
- This is the most common type you will create and use in your scripts.
2. Environment Variables
- Scope: Available system-wide and are inherited by all child processes and new shells.
- Convention: Always named in UPPERCASE.
Examples: PATH, HOME, USER, PWD.
You create one using the export command, which "exports" a local variable to the environment:
export MY_API_KEY="abc-123"3. Built-in Shell Variables
Special variables set automatically by the shell to provide information.
Examples:
- $SHELL: Path to the current shell (e.g., /bin/bash).
- $HOSTNAME: The name of the host machine.
- $?: The exit status (0-255) of the last command (0 means success).
- $1, $2: Positional parameters (arguments passed to your script).
How to Define Variables
Rules for Defining Variables:
1. No Spaces: The most critical rule. VAR="Hello" is correct. VAR = "Hello" is a fatal error.
2. Assignment: Use the equals sign (=) to assign a value.
3. Naming:
- Valid names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
- Names must start with a letter or an underscore.
- By convention, environment variables are ALL_CAPS, while local script variables are lowercase_or_mixed.
How to Access Variables
We will discuss how the defined variable can be accessed by the user.
1. Accessing variable
Variable data could be accessed by appending the variable name with '$' as follows:
#!/bin/bash
VAR_1="Devil"
VAR_2="OWL"
echo "$VAR_1$VAR_2"
Output:
DevilOWL
2. Unsetting Variables
The unset command directs a shell to delete a variable and its stored data from list of variables. It can be used as follows:
#!/bin/bash
var1="Devil"
var2=23
echo $var1 $var2
unset var1
echo $var1 $var2
Output:
DEVIL 23
23

Note: The unset command could not be used to unset read-only variables.
3. Read only Variables.
These variables are read only i.e., their values could not be modified later in the script. Following is an example:
#!/bin/bash
var1="Devil"
var2=23
readonly var1
echo $var1 $var2
var1=23
echo $var1 $var2
Output:
Devil 23
./bash1: line 8: var1: readonly variable
Devil 23

Now let us see all the above codes in action together. Following is a shell script that includes all the shell variables discussed above.
#!/bin/bash
#variable definitions
Var_name="Devil"
Var_age=23
# accessing the declared variables using $
echo "Name is $Var_name, and age is $Var_age."
# read-only variables
var_blood_group="O-"
readonly var_blood_group
echo "Blood group is $var_blood_group and read only."
echo "Error for read only variables, if trying to \
modify them."
echo
var_blood_group="B+"
echo
# unsetting variables
unset Var_age
echo "After unsetting var_age..."
echo
echo "Name is $Var_name, blood group is $var_blood_group\
and age is $Var_age..."
Output:

Few more examples in Shell Scripting and Shell Variable
We will discuss some scenario based examples that are often used in context of shell scripts.
How to Store User Data in a Variable?
#!/bin/bash
echo "Enter the length of the rectangle"
read length
echo "Enter the width of the rectangle"
read width
area=$((length * width))
echo "The are of the rectangle is: $area"
In this example the variables 'length', 'width' and 'area' are used to store user input and calculate the area of the rectangle.

In this 'echo' is a command used to print the statement and 'read' is a command used to take data from user and store it in a variable.
To Store and Display Message
We can write a script in which we will display a message to the user by looking at the time of the day. In this we can use shell variable to store and display our message.
#!/bin/bash
time=$(date +%H)
if [ $time -lt 12];then
message = "Good Morning User"
elif [ $time -lt 18 ];then
message = "Good Afternoon User"
else
message = "Good Evening User"
fi
echo "$message"hours

In this 'time' is a variable storing hours, 'date' is a command used to get the current time and '%H' is used to extract only hour's part. '-lt' is an operator used for numerical comparison it is a less than. 'fi' is used to mark the end of 'if' statement.
What is Shell and Its Type?
It is a program that provides a user interface that is used to access operating system services. Or we can say that it is an environment in which we can run our programs and shell scripts etc. It is the core of the operating system.
There are several different types of shell available. Some common types of shells include:
- Bourne Shell (sh): The original shell of UNIX operating system. It has been used for scripting purposes and also to provide basic commands.
- C Shell (csh): This is also a popular shell for UNIX operating system. As the name suggests, its syntax is similar to C programming language.
- Bourne-Again Shell (bash): It is a widely used shell for macOS and Linux operating systems. It is more advanced than the original Bourne shell and also has many features that are found in the Korn shell and C shell.
What is Shell Variable Used For?
Shell Variables are used to store data and information within a shell (terminal), and they are also used for controlling the behavior of program and scripts. Some of the common uses are:
- Setting environment variables.
- Storing configuration data.
- Storing temporary data.
- Passing arguments to scripts.
Shell Variable and Shell Scripting
Shell Variable is used in shell scripts for many functionalities like storing data and information, taking input from users, printing values that are stored. They are also used for storing data temporarily and storing output of commands.
- Shell Scripting is a way of writing scripts of programs that are executed in a terminal or shell.
- Basically, it is a program or script which is written with the help of variables mentioned in it.
- It is powerful because it can automate tasks, and in this one can use programming constructs that are available in shell, such as loops, conditionals and functions.
Shell Commands Sheet
| Syntax | What It Does |
| MY_VAR="value" | Define: Assigns a value. No spaces allowed. |
| echo "$MY_VAR" | Access (Safe): Replaces with value, handles spaces. (Recommended) |
| echo '$MY_VAR' | Access (Literal): Prints the literal string $MY_VAR. |
| echo $MY_VAR | Access (Unsafe): Replaces with value, but splits on spaces. |
| NOW=$(command) | Command Substitution: Stores the output of command in a variable. |
| read -p "Q: " VAR | User Input: Prompts the user and stores their answer in VAR. |
| readonly VAR | Makes the variable unchangeable. |
| unset VAR | Deletes the variable from memory. |
| export VAR | Makes the variable an Environment Variable. |
| $?, $1 | Built-in: Special shell variables (exit status, script arguments). |