Conditional logic is a cornerstone of programming and scripting that enables decision-making within scripts. In Linux shell scripting, conditional statements control the flow of execution based on specific conditions, allowing scripts to behave dynamically in response to different inputs or system states.
Basics of Conditional Statements in Shell Scripts
The primary conditional structures in shell scripting are:
Conditions are tested using expressions inside square brackets [ ] or double brackets [[ ]] with operators for comparison.
Syntax of if Statement
if [ condition ]
then
# commands to execute if condition is true
fiExample:
if [ $a -gt $b ]
then
echo "a is greater than b"
fiif...else Statement
Runs one set of commands if a condition is true, and another if it is false.
if [ condition ]
then
# commands if condition true
else
# commands if condition false
fiExample:
if [ $num -eq 10 ]
then
echo "Number is ten"
else
echo "Number is not ten"
fiif...elif...else Ladder
For multiple conditions, use elif (else if).
if [ condition1 ]
then
# commands if condition1 true
elif [ condition2 ]
then
# commands if condition2 true
else
# if no condition met
fiExample:
if [ $score -ge 90 ]
then
echo "Grade A"
elif [ $score -ge 80 ]
then
echo "Grade B"
else
echo "Grade C or below"
fiUsing the case Statement
The case statement matches a variable against multiple patterns, often used instead of multiple if statements for clarity.
Syntax:
case $variable in
pattern1)
# commands
;;
pattern2)
# commands
;;
*)
# default commands
;;
esacExample:
case $choice in
1) echo "You chose option 1";;
2) echo "You chose option 2";;
*) echo "Invalid option";;
esacCommon Operators for Conditions
| Type | Operator | Description | Example |
|---|---|---|---|
| Numeric | -eq | equal to | [ $a -eq $b ] |
| -ne | not equal to | [ $a -ne $b ] | |
| -gt | greater than | [ $a -gt $b ] | |
| -lt | less than | [ $a -lt $b ] | |
| String | = | equal to | [ "$str" = "abc" ] |
| != | not equal | [ "$str" != "abc" ] | |
| < | less than (in ASCII) | [ "$a" \< "$b" ] | |
| > | greater than (in ASCII) | [ "$a" \> "$b" ] | |
| File testing | -f file | is regular file | [ -f filename ] |
| -d dir | is directory | [ -d directory ] |
if [ $a -gt 0 ] && [ $a -lt 10 ]
then
echo "a is between 1 and 9"
fi