Shell Scripting: Conditionals
Objective
Write conditional logic in bash scripts using if/elif/else, the test command, string and numeric comparisons, and case statements.
Tools & Technologies
ifelifelsetest[[ ]]case
Key Commands
if [ -f file ]; then[[ $str == pattern ]]case $VAR intest -d /etc && echo 'exists'Architecture Overview
flowchart TD
START[Script starts] --> COND{[ condition ]\nor [[ ]] test}
COND -->|exit code 0\ntrue| IF_BODY[if block\nexecutes]
COND -->|exit code 1+\nfalse| ELIF{elif condition?}
ELIF -->|true| ELIF_BODY[elif block]
ELIF -->|false| ELSE[else block]
IF_BODY --> END[continue script]
ELIF_BODY --> END
ELSE --> END
style COND fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
Step-by-Step Process
01
if / elif / else
Basic conditional structure. Note the spaces inside [ ] — they are required.
#!/bin/bash
FILE='/etc/hosts'
if [ -f "$FILE" ]; then
echo "$FILE exists"
elif [ -d "$FILE" ]; then
echo "$FILE is a directory"
else
echo "$FILE not found"
fi
02
Test Operators
The test command ([ ]) supports file tests, string tests, and numeric comparisons.
# File tests
[ -f file ] # is regular file
[ -d dir ] # is directory
[ -r file ] # readable
[ -x file ] # executable
[ -s file ] # non-empty
# String tests
[ "$a" = "$b" ] # equal
[ "$a" != "$b" ] # not equal
[ -z "$str" ] # empty string
[ -n "$str" ] # non-empty string
# Numeric tests
[ $a -eq $b ] # equal
[ $a -ne $b ] # not equal
[ $a -lt $b ] # less than
[ $a -ge $b ] # greater or equal
03
[[ ]] — Enhanced Tests
Double brackets support regex, pattern matching, and safer string comparisons.
[[ "$str" == *.txt ]] # glob match
[[ "$str" =~ ^[0-9]+$ ]] # regex match
[[ -f file && -r file ]] # compound (no quotes needed)
04
case Statement
case is cleaner than nested if/elif for matching a single variable against multiple patterns.
read -p 'Enter choice [y/n/q]: ' CHOICE
case $CHOICE in
y|Y|yes)
echo 'Proceeding...'
;;
n|N|no)
echo 'Cancelled'
;;
q|Q)
echo 'Quit'
exit 0
;;
*)
echo 'Invalid choice'
;;
esac
Challenges & Solutions
- Spaces around [ ] are mandatory — [condition] causes syntax error
- = vs -eq: use = for strings, -eq for integers
Key Takeaways
- [[ ]] is bash-specific but more robust than [ ] — prefer it in bash scripts
- case is more readable than chains of elif for menu-style logic