In a shell script, you can use the if/else
statement to execute different blocks of code based on conditions. Here’s the general syntax for an if/else
statement in a shell script:
Basic Syntax:
if [ condition ]
then
# Code to run if condition is true
else
# Code to run if condition is false
fi
Explanation:
if
: Starts the conditional statement.[ condition ]
: The condition to be tested. This can be a comparison, file check, or other conditions.then
: Specifies the block of code to execute if the condition is true.else
: Specifies the block of code to execute if the condition is false.fi
: Closes theif/else
statement (in reverse order ofif
).
Example 1: Simple if/else
#!/bin/bash
number=10
if [ $number -gt 5 ]
then
echo "The number is greater than 5."
else
echo "The number is less than or equal to 5."
fi
Explanation:
$number -gt 5
: This condition checks if the variablenumber
is greater than 5.- The script will print “The number is greater than 5.” because 10 is greater than 5.
Example 2: If/else with string comparison
#!/bin/bash
name="John"
if [ "$name" == "Alice" ]
then
echo "Hello Alice!"
else
echo "Hello, stranger!"
fi
Explanation:
"$name" == "Alice"
: Compares the string inname
to"Alice"
.- Since
name
is “John”, the script will print “Hello, stranger!”.
Example 3: If/else with multiple conditions
You can use elif
(else if) to check multiple conditions.
#!/bin/bash
num=7
if [ $num -eq 10 ]
then
echo "Number is 10."
elif [ $num -lt 10 ]
then
echo "Number is less than 10."
else
echo "Number is greater than 10."
fi
Explanation:
-eq
: Tests if the numbers are equal.-lt
: Tests if the number is less than the specified value.- The script will print “Number is less than 10.” because
num
is 7.
Important Notes:
- When checking numbers in
bash
, you should use-eq
for equality,-gt
for greater than,-lt
for less than, etc. - When working with strings, use
==
or!=
for equality and inequality, respectively. - Use
"$variable"
(quotes around variables) to handle cases where variables may contain spaces or special characters.