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=Value

e.g

VarName=”Hi all”

TotalNumber=234

Example of Variable in Shell Script

#!/bin/sh

NameDisplay="Mohamadsiraj Raza"
echo $NameDisplay

OUTPUT :

Mohamadsiraj Raza

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

#!/bin/bash
echo "Where do you live:"
read Place
echo "Your Home town is  $Place!"

if reading more then one,

#!/bin/bash
echo "Eneter your firstname and lastname:"
read firstname lastname
echo "Hi! $firstname, $lastname !"

Variable Types

1) Local Variables

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

Example:

#!/bin/bash
Value=outside_function
function test {
local Value=local_inside_fnction
echo $Value
}
echo $Value
test
echo $Value
Output:

outside_function
local_inside_fnction
outside_function

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

Special variables in bash script or shell script

$0 – Output will be filename of the script.

Example: 
#!/bin/sh
echo "Output: $0"

Then
sudo ./File.sh
Output:
./File.sh

$n – display the argment where n is number ($1 first argument and $2 second argment)
$# – 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.

Example

#!/bin/sh

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

Run the script : sudo ./File.sh ken corner

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

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

#!/bin/bash
echo "Output for *:"
for argument in "$*"; do echo "$argument"; done
echo "-----\n"
echo "Output for @:"
for argument in "[email protected]"; do echo "$argument"; done
Output

$ sudo ./test.sh 1 2 "3 4"
Output for *:
1 2 3 4

Output for @:
1
2
3 4

You May Also Enjoy Reading This …

Leave a Reply

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