Conditionals
Bash scripting relies on conditional statements to implement logic-based flow control, enabling scripts to make decisions based on runtime evaluations. Conditional constructs like if-else, case, and the test command (also known as [) allow scripts to respond dynamically to system states, user inputs, or environmental variables. These structures are foundational for creating robust, adaptive automation.
if-else Statements¶
The if-else construct evaluates a condition and executes code blocks based on whether the condition is true or false. Conditions are typically evaluated using exit statuses (0 for success, non-zero for failure) or comparisons.
Syntax¶
if [ condition ]; then
# Code if condition is true
elif [ another_condition ]; then
# Code if another_condition is true
else
# Code if all conditions are false
fi
Example: File Existence Check¶
Here,-f checks if the path is a regular file. The script outputs a message based on the result.
Notes¶
- Always use
;or a newline to terminate the condition. - Use
eliffor additional conditional branches. - Avoid spaces around
[and]in test expressions.
case Statements¶
The case construct matches a variable against multiple patterns, making it ideal for handling discrete options (e.g., command-line flags). Patterns use shell globbing (*, ?, etc.).
Syntax¶
case $variable in
pattern1)
# Code for pattern1
;;
pattern2)
# Code for pattern2
;;
*)
# Default case
;;
esac
Example: Command-Line Option Handling¶
case "$1" in
--help|-h)
echo "Usage: script.sh [OPTIONS]"
;;
--version|-v)
echo "1.0.0"
;;
*)
echo "Unknown option: $1"
;;
esac
--help or -v and defaults to an error message for unknown inputs.
Notes¶
- Patterns are matched literally unless modified by
*or?. - Use
;;to terminate each case block. - The
*wildcard matches any unmatched input.
test Command ( [ )¶
The test command evaluates expressions for file properties, string comparisons, or arithmetic operations. It is often used inline with if statements.
Common Use Cases¶
| Expression | Description |
|---|---|
-f file |
True if file is a regular file |
-d file |
True if file is a directory |
-r file |
True if file is readable |
-w file |
True if file is writable |
-x file |
True if file is executable |
str1 == str2 |
True if strings are equal |
num1 -eq num2 |
True if numbers are equal |
Example: Numeric Comparison¶
This script outputs "10 is greater than 5" because-gt (greater than) evaluates to true.
Notes¶
- Use
&&or||for chaining conditions. - Avoid spaces around
[and]. - For string comparisons, use
==and ensure variables are quoted to prevent globbing.
Key takeaways¶
- Use
if-elsefor branching logic based on conditions. - Use
casefor matching variables against multiple patterns. - Use
test(or[) to evaluate file properties, strings, or arithmetic expressions. - Always quote variables in comparisons to avoid unintended globbing or expansion.
- Prioritize readability by structuring conditions clearly and avoiding nested complexity.