Open In App

Shell Scripting – Shell Variables

Improve
Improve
Like Article
Like
Save
Share
Report

A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing the shell variable scripting leads us to write strong and good shell scripts.

Rules for variable definition

 A variable name could contain any alphabet (a-z, A-Z), any digits (0-9), and an underscore ( _ ). However, a variable name must start with an alphabet or underscore. It can never start with a number. Following are some examples of valid and invalid variable names:

  • Valid Variable Names
ABC
_AV_3
AV232
  • Invalid variable names 
2_AN
!ABD
$ABC
&QAID

Note: It must be noted that no other special character except underscore can be used in a variable name because all other special characters have special meanings in Shell Scripting.

Defining Variables

Syntax

variable_name = <variable data>

Example 

num="1"
name="Devil"

These kinds of variables are scalar variables as they could hold one value at a time. 

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
Accessing variable

Example of Accessing variable

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
Unsetting Variables

Example of Unsetting Variables

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
Read only Variables.

Example of Read only Variables.

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:

All outputs

Variable Types

We can discuss three main types of variables:

1) Local Variable:

Variables which are specific to the current instance of shell. They are basically used within the shell, but not available for the program or other shells that are started from within the current shell. 

For example: 

`name=Jayesh`    

In this case the local variable is (name) with the value of Jayesh. Local variables is temporary storage of data within a shell script.

2) Environment Variable:

These variables are commonly used to configure the behavior script and programs that are run by shell. Environment variables are only created once, after which they can be used by any user.

For example:

`export PATH=/usr/local/bin:$PATH` would add `/usr/local/bin` to the beginning of the shell’s search path for executable programs.

3) Shell Variables:

Variables that are set by shell itself and help shell to work with functions correctly. It contains both, which means it has both, some variables are Environment variable, and some are Local Variables.

For example:

`$PWD` = Stores working directory 

`$HOME` = Stores user’s home directory

`$SHELL` = Stores the path to the shell program that is being used.

Few more examples in Shell Scripting and Shell Variable

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.

Giving input to variables

Giving input to the variable

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
To Store and Display Message by variables

Getting output based on the time of the day.

In this ‘time’ is a variable storing hours, ‘data’ 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:

  1. Bourne Shell (sh): The original shell of UNIX operating system. It has been used for scripting purposes and also to provide basic commands.
  2. 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.
  3. 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:

  1. Setting environment variables.
  2. Storing configuration data.
  3. Storing temporary data.
  4. Passing arguments to scripts.

What is 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.

Conclusion: 

Shell variables are an essential part of shell scripting. Shell variables allow us to use them anywhere in the script. In this article we have discussed the rules for defining scalar variables, unsetting variables, read-only variables and accessing variables. This article will serve as a helpful guide for beginners and those who want to understand how to write shell script must know how to work with shell variables.



Last Updated : 12 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads