In this post, lets discuss the use of conditionals in bash scripts.
What are conditionals?
At times you need to specify different courses of action to be taken in a shell script, depending on the success or failure of a command. The if construction allows you to specify such conditions.
The most compact
syntax of the if command is:
if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi
The TEST-COMMAND list is executed, and if its
return status is zero, the CONSEQUENT-COMMANDS
list is executed. The return status is the exit status of the last command
executed, or zero if no condition tested true.
The TEST-COMMAND often involves numerical or string
comparison tests, but it can also be any command that returns a status of zero
when it succeeds and some other status when it fails.
Syntax:
if [ expression 1 ];
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ];
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ];
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
Example:
#!/bin/sh
a=1
b=2
if [ $a == $b ];
then
echo "a is equal to b"
elif [ $a -gt $b ];
then
echo "a is greater than b"
elif [ $a -lt $b ];
then
echo "a is less than b"
else
echo "None of the conditions matched"
fi
Now let us see the
different ways to use expressions with numeric and strings.
( EXPRESSION )
EXPRESSION is true
! EXPRESSION
EXPRESSION is false
EXPRESSION1 -a EXPRESSION2
both EXPRESSION1 and EXPRESSION2
are true
EXPRESSION1 -o EXPRESSION2
either EXPRESSION1 or EXPRESSION2
is true
-n STRING
the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING
the length of STRING is zero
STRING1 = STRING2
the strings are equal
STRING1 != STRING2
the strings are not equal
INTEGER1 -eq INTEGER2
INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2
INTEGER1 is greater than or equal
to INTEGER2
INTEGER1 -gt INTEGER2
INTEGER1 is greater than INTEGER2
INTEGER1 -le INTEGER2
INTEGER1 is less than or equal to
INTEGER2
INTEGER1 -lt INTEGER2
INTEGER1 is less than INTEGER2
INTEGER1 -ne INTEGER2
INTEGER1 is not equal to INTEGER2
All these details
could be obtained from 'man test' command on linux/unix terminal.