You are currently viewing Variables in bash or shell script

Variables in bash or shell script

Variables in Bash or Shell script  

variable is used to temporary store data.In shell script variable has no data types. A variable in shell script can contain a number( 0 to 9) , a character (a to z or A to Z) , a string of characters or the underscore character ( _).



Defining Variables



VarName=”Hi all”


Example of Variable in Shell Script


NameDisplay="Mohamadsiraj Raza"

echo $NameDisplay


Mohamadsiraj Raza

Reading user input with read
Some time we need input from user so we use read command in bash

echo "Where do you live:"
read Place
echo "Your Home town is  $Place!"

From the above example we can get user input and store in variable ( Place) and display in the screen.

It may happen that we want to take more input from user.

echo "Eneter your firstname and lastname:"
read firstname lastname
echo "Hi! $firstname, $lastname !"

Variable Types in bash script

1) Local Variables

We use keyword local for denoting local variable its present in current instance


function test {
local Value=local_inside_fnction
echo $Value
echo $Value
echo $Value




2) Environment Variables
This variable is variable to any child process of the shell.

Special variables in bash script or shell script

$0 – Output will be filename of the script.

echo "Output: $0"



$n – display the argument where n is number ($1 first argument and $2 second argument)
$# – number of argument
$? – stats of last command run. 0 if command successful, and 1 if command unsuccessful.
$$ – It gives process id of the current working  shell
$! – It will give Process id of last background command which you have run.



echo "Name of File: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Total Number of Parameters : $#"

Run the script : ./ ken corner


Name of File: ./
First Parameter : ken
Second Parameter : corner
Total Number of Parameters : 2

Special Parameters $* and $@

Both will take and display unknown number of argument.

Difference between $@ and $*
$* – All the arguments are double quoted
$@ – All the arguments are individually double quoted

For example

echo "Output for *:"
for argument in "$*"; do echo "$argument"; done
echo "-----\n"
echo "Output for @:"
for argument in "$@"; do echo "$argument"; done
$ ./ 1 2 "3 4"
Output for *:
1 2 3 4

Output for @:
3 4

Script For Addition of two number

echo "Enter the First Number: "
read a
echo "Enter the Second Number: "
read b
x=$(expr "$a" + "$b")
echo $a + $b = $x

Bash script for $? which give status of last run command.


cp -R fileName /opt/
if [ $RESULT -eq 0 ];
echo "File copied"

echo "Unable to copy the file"


In this above example we used $? to check that command cp -R worked or not ,it command is successful then it will return 0 or if it fail then it will return 1

You May Also Enjoy Reading This …

Leave a Reply