Variable Assignment and Substitution in Linux Shell Scripting


Variable

A variable is a value that can change, depending on conditions or on information passed to the program.


Assigning a Variable 



A variable can be assigned by variable name after that = and then variable value.

$ variable=Hello

Note that there should not be any space on either side of =

If there is any space then see how it work

Variable  =52
The shell runs variable as a command and =52 as option

Variable=  52
Here shell treats variable as environment variable and runs value as a command.


Variable Assignment



Variable can be assigned by different ways

1. Normal Assignment


a=5

2. Using let

let a=10+5

3. using for loop

for a in 1 2 3 4
do
echo -n "$a "
done

4. using read

echo -n "Enter \"a\" "
read a

5. Using back tilt (`)

a=`echo hi`
echo $a
output: hi

a=`pwd`
echo $a
it prints present working dorectory

a=`echo pwd`
echo $a
output: pwd

6. Null value assignment.

Setting a null value.

hello= 
echo "\$hello = $hello"
$hello =



Retrieving a variable

A variable can be retrieved by $variablename.

variable=hello
$ echo variable                  #variable cannot be retrieved here
variable
$ echo $variable
Hello


Variable substitution

Assign variable
x=52

Substitute variable

foo=$x




No comments: