Chapter 7: Conditionals
Scripting is not just about running commands in a line; it is about making decisions based on data. In the shell, "truth" is determined by Exit Codes. A successful command returns 0, which the shell interprets as True.
I. The Test Command: [ vs [[
There are two ways to write conditions in Bash. Understanding the difference is crucial for writing robust scripts.
1. The Old Test: [ ... ]
This is actually a command (usually /usr/bin/[). It is highly compatible but has limitations:
- Requires quoting variables to handle spaces.
- Cannot use
&&or||inside the brackets.
2. The New Test: [[ ... ]]
This is a Bash keyword (not a command). It is preferred for all modern Bash scripts:
- Handles spaces in variables automatically (less quoting needed).
- Supports Pattern Matching and Regex.
- Allows
&&and||inside the brackets.
II. Decision Flow Logic
III. Common Test Operators
1. String Tests
[[ $A == $B ]]: True if strings are equal.[[ $A != $B ]]: True if strings are NOT equal.[[ -z $A ]]: True if string is empty.[[ $A =~ ^[0-9]+$ ]]: True if string matches a Regex (digits only).
2. File Tests
[[ -f $FILE ]]: Is it a regular file?[[ -d $DIR ]]: Is it a directory?[[ -e $NAME ]]: Does it exist at all?[[ -s $FILE ]]: Is the file not empty?
IV. Multi-Branch Logic: case
When you have many possible values for a single variable, an if-elif-else chain becomes messy. The case statement is much cleaner.
#!/usr/bin/env bash
read -p "Enter extension (mp3, jpg, txt): " EXT
case "$EXT" in
mp3)
echo "Processing audio..."
;;
jpg|jpeg|png)
echo "Processing image..."
;;
txt|md)
echo "Processing text..."
;;
*)
echo "Unknown format!"
exit 1
;;
esac
V. Arithmetic Context: (( ... ))
For numeric comparisons, use double parentheses. This allows you to use standard mathematical operators like >, <, >=, and ==.
SCORE=85
if (( SCORE >= 90 )); then
echo "Grade: A"
elif (( SCORE >= 80 )); then
echo "Grade: B"
else
echo "Keep trying!"
fi
In the next chapter, we'll learn how to repeat tasks efficiently using Loops.