The case Statement
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 9 of 39.
A case statement compares one value against a list of patterns and runs the commands under the first one that matches. Each branch ends with ;;, and esac (case spelled backwards) closes the statement.
#!/bin/bash
case "$1" in
start)
echo "Starting the server"
;;
stop|halt)
echo "Stopping the server"
;;
*.conf)
echo "Loading settings from $1"
;;
*)
echo "Unknown command: $1"
;;
esacbash server.sh halt prints Stopping the server, because | lets one branch take several words. Patterns are globs, as in [[ ]]: bash server.sh site.conf matches *.conf and prints Loading settings from site.conf. *) matches anything, so it goes last and catches every value the other branches missed: bash server.sh restart prints Unknown command: restart. Bash stops at the first match and skips the branches below it.
Challenge
MediumWrite a script that prints a shop's opening hours for a day.
- Open
hours.sh. It takes a short day name as its first argument:mon,tue,wed,thu,fri,satorsun. - Use one
casestatement on"$1". - For
montofri, printDAY: open 9 to 18, all five days in one branch. - For
sat, printDAY: open 10 to 14. Forsun, printDAY: closed. - For anything else, print
Unknown day: VALUEto stderr and exit with code1. - Save the file.
Try it: run bash hours.sh mon. It prints:
mon: open 9 to 18Then run bash hours.sh monday; echo "exit $?". Only the short names match:
Unknown day: monday
exit 1Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground