Decisions and Status
Case Patterns
Matching Commands
A case statement compares one value against several shell patterns. It keeps command dispatch readable.
Program
Play the script to see the restart pattern choose the cycle action.
case_patterns.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
command="restart"
case "$command" in
start) action="boot" ;;
stop) action="halt" ;;
restart) action="cycle" ;;
*) action="unknown" ;;
esac
echo "$action"
command ← restart
3command="restart"4case "$command" invalues this steprestartcommandpattern ← restart
3command="restart"4case "$command" in5 start) action="boot" ;;values this steprestartpatternrestartcommandaction ← cycle
6stop) action="halt" ;;7restart) action="cycle" ;;8*) action="unknown" ;;values this stepcycleactionecho "$action"
9esac10echo "$action"outputcyclevalues this stepcycleaction
Follow the Pattern
commandis set torestart.- The
casestatement checksstart, thenstop, thenrestart, then*. restartmatches therestartpattern.- That branch sets
actiontocycle. - The script prints
cycle. | pattern checked | matchesrestart? | action | | --- | --- | --- | |start| no | - | |stop| no | - | |restart| yes |cycle| |*| not reached | - |
case
`case` selects the first pattern that matches a value.
fallback pattern
`*` catches values that do not match an earlier pattern.
Exercise: case_patterns.sh
Reproduce cycle, then identify the exact pattern that matches command=restart.