Monday 13 February 2012

Variables in Linux Shell Script

Well, this has been a bit tricky for me so I decided to put it on my blog so that it can be helpful to you guys.

First of all, How to define a variable?


count=0

There! I've just defined a variable count with 0 as its initial value.
Now, How do you print value of a variable?

echo "$count"

or

echo $count

Next. How do you perform calculations on a variable?
Okay. So assume that you have two variables called val1 and val2 with values 3 and 4 respectively. Now, you want val3 to have the addition of val1 and val2. So,


val1=3
val2=4
val3=`expr $val1 + $val2`

Similarly, to do subtraction:

val4=`expr $val1 - $val2`


Note that spaces are very important here.

Now, if you wish to assign value returned by a command to a variable, then it works by doing:

wcount=`wc -w myfile.txt`

anything between ` and ` will be executed as linux command and the value returned by that command will be assigned back to the variable to left.

No comments:

Post a Comment