Linux Basics: Match Text with Bash case Patterns
A case statement makes a small text classifier readable. Patterns match strings directly; these examples do not search the filesystem.
These examples were tested on Linux with GNU Bash 5.2.37. Use Bash rather than sh. No packages or administrator access are needed.
Prepare a scratch directory
You need Bash, a text editor, and the mktemp, rm, and rmdir utilities. Keep using the same terminal. Save each named source file in this scratch directory before running its command. Calling bash explicitly avoids changing executable permissions.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 11. Classify names by suffix
Save this as case-extension.sh:
#!/usr/bin/env bash
for name in report.csv photo.jpg archive.tar.gz notes.txt; do
case "$name" in
*.tar.gz) kind=archive ;;
*.csv) kind=data ;;
*.jpg|*.png) kind=image ;;
*) kind=other ;;
esac
printf '%s: %s\n' "$name" "$kind"
doneRun it:
bash case-extension.shOutput:
report.csv: data
photo.jpg: image
archive.tar.gz: archive
notes.txt: otherPlace specific patterns before broad ones. | joins alternatives; * matches any string. The first matching clause wins when clauses end with ;;.
2. Recognize a few explicit answers
Save this as case-answer.sh:
#!/usr/bin/env bash
for answer in yes Y no maybe; do
case "$answer" in
yes|YES|y|Y) result=accepted ;;
no|NO|n|N) result=declined ;;
*) result='please answer yes or no' ;;
esac
printf '%s: %s\n' "$answer" "$result"
doneRun it:
bash case-answer.shOutput:
yes: accepted
Y: accepted
no: declined
maybe: please answer yes or noMatching is case-sensitive by default. Explicit alternatives keep accepted values visible. This script only classifies sample text; it does not perform an action based on the answer.
3. Reject anything except ASCII digits
Save this as case-digits.sh:
#!/usr/bin/env bash
LC_ALL=C
for value in 42 '' 7x -3 008; do
case "$value" in
''|*[!0-9]*) result=invalid ;;
*) result=digits ;;
esac
printf '<%s>: %s\n' "$value" "$result"
doneRun it:
bash case-digits.shOutput:
<42>: digits
<>: invalid
<7x>: invalid
<-3>: invalid
<008>: digitsThe empty-string alternative rejects missing input. [!0-9] matches a non-digit, so the surrounding stars detect one anywhere. These are shell patterns, not regular expressions: [0-9]* alone would also accept 7x. This validates text only, not a numeric range.
Clean up
In the same terminal, remove only the example files, return to your original directory, and remove the empty scratch directory:
rm -- case-extension.sh case-answer.sh case-digits.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirReference
See the GNU Bash manual: Conditional Constructs for the relevant shell behavior. The installed Bash help command also documents these builtins.
Acknowledgements
This post was created with assistance from AI.