How to do the decision-making in Unix/Linux shell

Decision-making is the act of performing different actions based on different conditions.

The following are the two types of decision-making statements we can use in Unix/Linux shell:

  1. The if-else statement: If-else statements are useful to take a path from a given set of paths based on the given conditions.
  • if-fi: The if block is executed if the specified condition is true.
  • if-else-fi: The if block is executed if the specified condition is true. Otherwise, the else block is executed.
  • if-elif-else-fi: The if block is executed if the condition specified in the if statement is true. Otherwise, the next elif condition is checked. The elif block is executed if the condition specified in the elif statement is true. The process goes on for the remaining elif statements until no condition is satisfied. If none of the conditions of if or elif statements are satisfied, the else block is executed.
  1. The case-sac statement: Case-sac statements are similar to switches. They are useful when all of the different branches only depend on the value of a single input variable.

Comparison operators

1. Binary operators

  • String comparison operators compare strings. The following illustration shows some valid string comparisons.
  • Numeric comparison operators compare numeric values. The table below shows some valid numeric comparisons.
Comparison Interpretation
$x -eq $y $x is equal to $y
$x -ne $y $x is not equal to $y
$x -lt $y $x < $y
$x -gt $y $x > $y
$x -le $y $x <= $y
$x -ge $y $x >= $y

2. Logical operators

Logical operators are used to combine different binary operators.

  • AND operator: &&
  • OR operator: ||
  • NOT operator: !

Code

The codes below explain the usage of both decision-making methods.

1. The if-else statement

score=73
if [ "$score" -ge 90 ]; then
echo "A*"
elif [ "$score" -ge 80 ]; then
echo "A"
elif [ "$score" -ge 70 ]; then
echo "B"
elif [ "$score" -ge 60 ]; then
echo "C"
elif [ "$score" -ge 50 ]; then
echo "D"
else
echo "F"
fi

2. The case-sac statement

temp="Algorithms"
case "$temp" in
"Databases") echo "Databases are simply magical!";;
"Operating Systems") echo "Operating Systems are awesome :)";;
"Algorithms") echo "I love Algorithms <3";;
esac

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved