Understanding Bash if and case Conditional Statements
Bash if Statement Syntax
Single Branch (if-then)
if <condition>; then
command(s)
fi
Or on multiple lines:
if <condition>
then
command(s)
fi
Double Branch (if-then-else)
if <condition>; then
commands_if_true
else
commands_if_false
fi
Multi-Branch (if-then-elif-else)
if <condition1>; then
commands_for_1
elif <condition2>; then
commands_for_2
elif <condition3>; then
commands_for_3
else
commands_for_fallback
fi
Key points:
- The condition can be a
testexpression,[],[[ ]],(()), or even a direct command. - Every
ifblock must start withif, includethen, and end withfi. elifbranches also require athen; theelsebranch does not usethen.
Converting Conditional Expressions to if
A chained logical expression using && and || can be rewritten as a if statement. For example:
[ -f /etc/passwd ] && echo "exists" || echo "not found"
Is equivalent to:
if [ -f /etc/passwd ]; then
echo "exists"
else
echo "not found"
fi
This pattern applies to any conditional expression.
Bash case Statement
Overview
The case statement is an alternative to a long if-elif-else chain. It is especially useful for scripts that handle multiple discrete values, such as service startup scripts. However, if is more general—it can handle comparisons, tests, and complex conditions, whereas case is best for matching fixed patterns.
Syntax
case "$variable" in
pattern1)
commands_for_pattern1
;;
pattern2)
commands_for_pattern2
;;
*)
default_commands
;;
esac
Explanation:
- If the variable matches
pattern1, the commands under it run until;;is encountered, then thecaseblock ends. - If no pattern matches, the
*)branch (which is optional) executes; its;;can be omitted. - Patterns support wildcards, pipe (
|) for alternatives, and regular expressions.
Practical Example
Create a script /server/scripts/b7.sh:
#!/bin/bash
read -p "Please enter a number [1-9]: " num
case $num in
1)
echo "The number is 1"
;;
2)
echo "The number is 2"
;;
[3-9])
echo "The number is $num"
;;
*)
echo "Error: please enter a numeric value between 1 and 9."
;;
esac
Running the script:
$ sh /server/scripts/b7.sh
Please enter a number [1-9]: 1
The number is 1
$ sh /server/scripts/b7.sh
Please enter a number [1-9]: 5
The number is 5
$ sh /server/scripts/b7.sh
Please enter a number [1-9]: g
Error: please enter a numeric value between 1 and 9.