Variables in Bash and 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


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

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.

Variable Types in bash script

1) Local Variables

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




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.


$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.


Run the script : ./ ken corner


Special Parameters $* and [email protected]

Both will take and display unknown number of argument.

Difference between [email protected] and $*
$* – All the arguments are double quoted
[email protected] – All the arguments are individually double quoted

For example

Script For Addition of two number

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


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

Your email address will not be published. Required fields are marked *