How does `case` work, and when is it better than `if/elif`?
BeginnerConceptArrays, conditionals and loops
Answer
case matches a word against glob patterns, top to bottom, and runs the first match.
case $1 in
start|up) start_app ;;
stop|down) stop_app ;;
deploy) shift; deploy "$@" ;;
-h|--help) usage; exit 0 ;;
*.tar.gz) extract "$1" ;;
*) echo "unknown command: $1" >&2; usage >&2; exit 2 ;;
esac
It is clearer than chained if for subcommands, file types and environment names, and it works in POSIX sh. Bash also supports ;& (fall through) and ;;& (continue testing).
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate