🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Case

A case statement matches one value against a list of patterns. The block under the first matching pattern runs.

One Match

The value matches the first pattern. Its line prints and the rest is skipped.

fruit="apple"
case "$fruit" in
  apple)
    echo "You picked an apple"
    ;;
  *)
    echo "You picked something else"
    ;;
esac

Several Patterns

The same script shape checks a weekday value. The value Mon matches the first pattern.

day="Mon"
case "$day" in
  Mon)
    echo "The week starts"
    ;;
  Sat)
    echo "The weekend starts"
    ;;
  *)
    echo "A regular day"
    ;;
esac

A Different Input

This script keeps the shape from the last one. The new value Sat hits a different arm.

day="Sat"
case "$day" in
  Mon)
    echo "The week starts"
    ;;
  Sat)
    echo "The weekend starts"
    ;;
  *)
    echo "A regular day"
    ;;
esac

Example

choice=2
case "$choice" in
  1)
    echo "You chose tea"
    ;;
  2)
    echo "You chose coffee"
    ;;
  3)
    echo "You chose juice"
    ;;
  *)
    echo "Please pick 1, 2, or 3"
    ;;
esac

Key points

  • A case statement starts with the word case.
  • Each pattern ends with a closing parenthesis.
  • Two semicolons end each pattern block.
  • The star pattern matches any value.
  • The word esac ends the whole statement.
  • Only the first matching block runs.

In this example, the choice holds 2 and matches the second pattern. The star arm would catch any value outside the menu.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which pattern works as the catch-all in a case statement?