Menu
CoddyTech

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"
    ;;
esac

bash 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 icon

Challenge

Medium

Write a script that prints a shop's opening hours for a day.

  1. Open hours.sh. It takes a short day name as its first argument: mon, tue, wed, thu, fri, sat or sun.
  2. Use one case statement on "$1".
  3. For mon to fri, print DAY: open 9 to 18, all five days in one branch.
  4. For sat, print DAY: open 10 to 14. For sun, print DAY: closed.
  5. For anything else, print Unknown day: VALUE to stderr and exit with code 1.
  6. Save the file.

Try it: run bash hours.sh mon. It prints:

mon: open 9 to 18

Then run bash hours.sh monday; echo "exit $?". Only the short names match:

Unknown day: monday
exit 1

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground