0
0
Bash Scriptingscripting~5 mins

if-then-fi structure in Bash Scripting

Choose your learning style9 modes available
Introduction
The if-then-fi structure helps your script make decisions by running commands only when certain conditions are true.
Check if a file exists before trying to read it.
Run a command only if a user is logged in.
Decide what message to show based on a number's value.
Verify if a program is installed before using it.
Syntax
Bash Scripting
if [ condition ]
then
  commands
fi
The 'fi' word ends the if block; it's 'if' spelled backward.
Conditions are placed inside square brackets with spaces around them.
Examples
Checks if 'myfile.txt' exists as a file, then prints a message.
Bash Scripting
if [ -f myfile.txt ]
then
  echo "File exists"
fi
Greets the user only if their username is 'admin'.
Bash Scripting
if [ "$USER" = "admin" ]
then
  echo "Welcome, admin!"
fi
Prints a message if the variable 'number' is more than 10.
Bash Scripting
if [ "$number" -gt 10 ]
then
  echo "Number is greater than 10"
fi
Sample Program
This script asks the user to enter a number. If the number is greater than zero, it prints a message saying it's positive.
Bash Scripting
#!/bin/bash

read -p "Enter a number: " num

if [ "$num" -gt 0 ]
then
  echo "You entered a positive number."
fi
OutputSuccess
Important Notes
Always put spaces after '[' and before ']' in conditions.
Use '-f' to check if a file exists, '-d' for directories, and '-gt' for numeric comparisons.
Remember to make your script executable with 'chmod +x script.sh' before running.
Summary
The if-then-fi structure lets your script choose actions based on conditions.
Conditions go inside square brackets with spaces around them.
End the if block with 'fi' to close it properly.