bhylu.com

Advertisements

Bash case

Dispatch a small set of supported actions and reject the rest.

How it works

case matches a value against shell patterns. It is useful for a compact command interface with known actions, including an explicit unsupported branch. These patterns are not regular expressions. Avoid routing arbitrary action text into eval or into a constructed command string; map it to fixed operations and pass variable data as separate arguments.

Run the code

Reviewed with Git for Windows Bash 5.2.37. Open Git Bash, save the download with LF line endings in a separate learning folder, check it with bash -n lesson-name.sh, then run bash lesson-name.sh using the actual filename. Bash 4 or newer is required for the full course. Linux-only notes identify unavailable tools or POSIX behaviour. There is no Bash browser runner; Apache and MySQL are not required.

This complete example was executed in the stated local review environment.

Download complete source

Example

case.sh

#!/usr/bin/env bash
set -u
set -o pipefail
export LC_ALL=C
action="preview"
case "$action" in
    preview) printf "Preview only; no files changed\n" ;;
    build) printf "Build action selected\n" ;;
    *) printf "Unsupported action\n" >&2; exit 2 ;;
esac

Expected result

Preview only; no files changed

The selected action has no filesystem side effects. An unsupported value produces an error status rather than falling through into a default build. Extend the list deliberately when adding actions, and test that a misspelling cannot trigger a destructive operation. Pattern order matters when several patterns overlap.

Primary technical reference: Bash documentation.