0
0
Bash Scriptingscripting~5 mins

Why conditionals branch script logic in Bash Scripting

Choose your learning style9 modes available
Introduction
Conditionals let a script choose different actions based on information it checks. This helps scripts make decisions like a person would.
Check if a file exists before using it.
Decide what message to show based on user input.
Run different commands depending on system settings.
Skip steps if a condition is not met.
Handle errors by checking if a command worked.
Syntax
Bash Scripting
if [ condition ]; then
  commands
elif [ another_condition ]; then
  other_commands
else
  default_commands
fi
Use spaces around brackets and conditions for correct syntax.
The 'fi' keyword ends the if statement.
Examples
Checks if 'myfile.txt' exists and prints a message if true.
Bash Scripting
if [ -f myfile.txt ]; then
  echo "File exists"
fi
Greets the admin user differently from others.
Bash Scripting
if [ "$USER" = "admin" ]; then
  echo "Welcome, admin!"
else
  echo "Access denied"
fi
Prints age group based on the value of 'age'.
Bash Scripting
if [ "$age" -ge 18 ]; then
  echo "Adult"
elif [ "$age" -ge 13 ]; then
  echo "Teenager"
else
  echo "Child"
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 "You entered a positive number."
elif [ "$num" -lt 0 ]; then
  echo "You entered a negative number."
else
  echo "You entered zero."
fi
OutputSuccess
Important Notes
Always put spaces after '[' and before ']' in conditions.
Use '-gt', '-lt', '-eq' for numeric comparisons, not '>' or '<'.
Test your script with different inputs to see all branches work.
Summary
Conditionals let scripts pick what to do based on checks.
They help scripts act like simple decision-makers.
Use if, elif, and else to cover different cases.