The case Statement
Prerequisites: Conditionals: if and tests
case matches one value against several patterns — cleaner than a
long if/elif chain, and ideal for handling commands and file types.
Syntax
case "$value" in
pattern1)
commands ;;
pattern2 | pattern3)
commands ;;
*)
default commands ;;
esac
Example
for file in photo.JPG report.pdf notes.txt song.mp3 archive.tar.gz; do
case "$file" in
*.jpg | *.JPG | *.png) type="image" ;;
*.pdf | *.docx) type="document" ;;
*.txt | *.md) type="text" ;;
*.tar.gz | *.zip) type="archive" ;;
*) type="other" ;;
esac
echo "$file: $type"
done
Expected output
photo.JPG: image
report.pdf: document
notes.txt: text
song.mp3: other
archive.tar.gz: archive
- Each pattern ends with
), and each branch ends with;;. - Patterns use wildcards;
|separates alternatives. *)catches everything else — the default.- The block ends with
esac("case" backwards).
Handling subcommands
A very common use: scripts that take a command as their first argument.
cat > service.sh <<'EOF'
case "$1" in
start) echo "Starting..." ;;
stop) echo "Stopping..." ;;
restart) echo "Restarting..." ;;
*) echo "Usage: $0 {start|stop|restart}" >&2; exit 1 ;;
esac
EOF
bash service.sh start
bash service.sh jump
Starting...
Usage: service.sh {start|stop|restart}
Practice
Write a case statement that prints weekend for Sat or Sun and
weekday for anything else, and test it with day=Sun.
Show solution
day="Sun"
case "$day" in
Sat | Sun) echo "weekend" ;;
*) echo "weekday" ;;
esac
weekend