If-else statements in Bash are fundamental control structures that allow you to make decisions in your shell scripts. They enable your script to execute different code blocks based on specified conditions.
The basic syntax of an if-else statement in Bash is as follows:
if [ condition ]
then
# Code to execute if condition is true
else
# Code to execute if condition is false
fi
The fi
keyword marks the end of the if-else block, which is "if" spelled backwards.
Here's a simple example that checks if a number is positive:
#!/bin/bash
number=10
if [ $number -gt 0 ]
then
echo "The number is positive"
else
echo "The number is not positive"
fi
Bash uses various operators for comparisons in if statements:
-eq
: Equal to-ne
: Not equal to-gt
: Greater than-lt
: Less than-ge
: Greater than or equal to-le
: Less than or equal toYou can use elif
(else if) to check multiple conditions:
#!/bin/bash
age=25
if [ $age -lt 18 ]
then
echo "You are a minor"
elif [ $age -ge 18 ] && [ $age -lt 65 ]
then
echo "You are an adult"
else
echo "You are a senior citizen"
fi
Bash provides operators for file testing in if statements:
-e
: File exists-f
: Regular file-d
: Directory-r
: Readable-w
: Writable-x
: ExecutableFor string comparisons, use double square brackets:
#!/bin/bash
name="John"
if [[ "$name" == "John" ]]
then
echo "Hello, John!"
else
echo "You're not John"
fi
[[ ]]
for string comparisons and pattern matching.(( ))
instead of [ ]
.To further enhance your Bash scripting skills, explore these related topics:
By mastering if-else statements, you'll be able to create more dynamic and responsive Bash scripts, enhancing your shell scripting capabilities.