0
0
Bash Scriptingscripting~5 mins

if-then-else in Bash Scripting

Choose your learning style9 modes available
Introduction
Use if-then-else to make decisions in your script. It helps your script choose what to do based on conditions.
Check if a file exists before using it.
Decide what message to show based on user input.
Run different commands depending on system status.
Verify if a number is positive or negative.
Choose actions based on the time of day.
Syntax
Bash Scripting
if [ condition ]
then
  commands
else
  other_commands
fi
Use spaces around brackets: [ condition ] is required.
End the if block with fi (which is if spelled backward).
Examples
Checks if the variable name is Alice, then prints a greeting or a question.
Bash Scripting
if [ "$name" = "Alice" ]
then
  echo "Hello, Alice!"
else
  echo "Who are you?"
fi
Checks if file.txt exists and prints a message accordingly.
Bash Scripting
if [ -f "file.txt" ]
then
  echo "File exists."
else
  echo "File not found."
fi
Sample Program
This script asks the user for a number and tells if it is positive or not.
Bash Scripting
#!/bin/bash

read -p "Enter a number: " num

if [ "$num" -gt 0 ]
then
  echo "The number is positive."
else
  echo "The number is zero or negative."
fi
OutputSuccess
Important Notes
Always put spaces after [ and before ] in conditions.
Use -gt for 'greater than' when comparing numbers.
Quotes around variables prevent errors if they are empty.
Summary
if-then-else lets your script choose between two paths.
Conditions go inside [ ] with spaces around them.
End the block with fi to close the if statement.