If statements 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:
if [ $val1 -eq 5 ]
     Code here to do some stuff
     If above condition is false, then code here gets executed

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 Operator Linux 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" ]
     Code here to do some stuff

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.