0
0
Bash Scriptingscripting~5 mins

if-elif-else in Bash Scripting

Choose your learning style9 modes available
Introduction
Use if-elif-else to make decisions in your script based on different conditions.
Check if a file exists before processing it.
Decide what message to show based on user input.
Run different commands depending on the time of day.
Validate if a number is positive, negative, or zero.
Syntax
Bash Scripting
if [ condition ]; then
  # commands if condition is true
elif [ another_condition ]; then
  # commands if another_condition is true
else
  # commands if none of the above conditions are true
fi
Use spaces around brackets and conditions, like [ condition ].
End the if block with fi to close it.
Examples
Checks if age is 18 or more, then prints a message.
Bash Scripting
if [ "$age" -ge 18 ]; then
  echo "You are an adult."
else
  echo "You are a minor."
fi
Prints different messages based on the color value.
Bash Scripting
if [ "$color" = "red" ]; then
  echo "Stop"
elif [ "$color" = "yellow" ]; then
  echo "Caution"
else
  echo "Go"
fi
Sample Program
This script asks the user for a number and tells if it is positive, negative, or zero.
Bash Scripting
#!/bin/bash

read -p "Enter a number: " num

if [ "$num" -gt 0 ]; then
  echo "The number is positive."
elif [ "$num" -lt 0 ]; then
  echo "The number is negative."
else
  echo "The number is zero."
fi
OutputSuccess
Important Notes
Always quote variables inside [ ] to avoid errors if they are empty.
Use -eq, -ne, -gt, -lt, -ge, -le for numeric comparisons.
Use = or != for string comparisons inside [ ].
Summary
if-elif-else helps your script choose what to do based on conditions.
Remember to close the block with fi.
Use proper spacing and quoting to avoid syntax errors.