Monday, 13 February 2012

Conditions in Linux Shell Script

If statements are important in any programming language. I had a bit of hard time while doing if statements in linux since they are different than those in a conventional programming language. First of all, an if statement to compare whether a value in a variable val1 is equal to 5 is like:

val1=5
if [ $val1 -eq 5 ]
then
     Code here to do some stuff
else
     If above condition is false, then code here gets executed
fi
Note that spaces are important when defining condition. $val1 refers to the variable and -eq simply implies equal to operator to compare if the $val1 is equal to 5.


Seems pretty easy? It is. Other conditional operators are:


Conditional OperatorLinux Equivalent
Greater than-gt
Less than-lt
Equal to-eq
Not equal to-ne

Now, if I want to compare strings, for instance, if variable answer is equal to "yes" then the code will be as follows:


if [ "$val" = "yes" ]
then
     Code here to do some stuff
fi


Again, spaces are important here.
In here, '=' can easily be replaced by conventional conditional operators like '>' or '<' or '!=' etc.

No comments:

Post a Comment