Making Decisions in Bash
Conditionals allow your scripts to make decisions โ to execute different blocks of code depending on whether a condition is true or false. This is where scripting really starts to feel powerful.
The if Statement
The basic syntax uses if, then, and fi (which is "if" backwards).
if [ condition ]; then
# commands if true
elif [ another_condition ]; then
# commands if first was false, this is true
else
# commands if all conditions are false
fiTest Command: [ ] vs [[ ]]
The single brackets [ ] are equivalent to the test command. Double brackets [[ ]] are a Bash-specific enhancement with more features and fewer pitfalls.
# These are equivalent:
if [ -f "myfile.txt" ]; then echo "Exists"; fi
if test -f "myfile.txt"; then echo "Exists"; fi
# [[ ]] is more powerful (Bash-specific)
if [[ "$name" == "Alice" && -f "config.txt" ]]; then
echo "Alice has a config file"
fi[[ ]] over [ ] in Bash scripts. It handles empty variables better, supports pattern matching, and doesn't require quoting variables as strictly.
String Comparisons
str="hello"
# Equality
[[ "$str" == "hello" ]] # true
[[ "$str" != "world" ]] # true
# Empty / non-empty
[[ -z "$str" ]] # true if string is empty (zero length)
[[ -n "$str" ]] # true if string is non-empty
# Pattern matching (only in [[ ]])
[[ "$str" == h* ]] # true โ starts with hNumeric Comparisons
a=10
b=20
[[ $a -eq $b ]] # equal
[[ $a -ne $b ]] # not equal
[[ $a -lt $b ]] # less than
[[ $a -gt $b ]] # greater than
[[ $a -le $b ]] # less than or equal
[[ $a -ge $b ]] # greater than or equal
# Example
if [[ $a -lt $b ]]; then
echo "$a is less than $b"
fiFile Tests
Bash provides built-in operators to check file properties:
[[ -f "file" ]] # true if file exists and is a regular file
[[ -d "dir" ]] # true if directory exists
[[ -e "path" ]] # true if path exists (file or directory)
[[ -r "file" ]] # true if file is readable
[[ -w "file" ]] # true if file is writable
[[ -x "file" ]] # true if file is executable
[[ -s "file" ]] # true if file is not empty
# Example
if [[ -d "$HOME/projects" ]]; then
echo "Projects directory exists"
else
mkdir "$HOME/projects"
echo "Created projects directory"
fiThe case Statement
case is Bash's version of a switch statement โ great for matching a variable against multiple patterns.
read -p "Enter a fruit: " fruit
case "$fruit" in
apple)
echo "An apple a day..."
;;
banana|orange)
echo "Tropical fruit!"
;;
*)
echo "Unknown fruit: $fruit"
;;
esaccase block must end with ;;. The *) pattern is the default/catch-all case.
Try It Yourself
Summary
You now know how to write if/elif/else/fi statements, the difference between [ ] and [[ ]], how to compare strings and numbers, test file properties, and use case statements for pattern matching.