$ run as a normal user# run as root (or with sudo)
Write a case statement
case checks a word against patterns, from top to bottom. The first matching pattern wins; ;; ends its commands.
case word in
pattern1) commands ;;
pattern2) commands ;;
*) commands ;;
esac#!/bin/bash
# case-menu: a menu driven system information program
clear
echo "
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
"
read -p "Enter selection [0-3] > "
case "$REPLY" in
0) echo "Program terminated."
exit
;;
1) echo "Hostname: $HOSTNAME"
uptime
;;
2) df -h
;;
3) if [[ "$(id -u)" -eq 0 ]]; then
echo "Home Space Utilization (All Users)"
du -sh /home/*
else
echo "Home Space Utilization ($USER)"
du -sh "$HOME"
fi
;;
*) echo "Invalid entry" >&2
exit 1
;;
esacThe same menu with if needed many more lines.
Use patterns
case patterns are like the shell's wildcards (pathname expansion). *) at the end catches everything else.
| Pattern | Matches |
|---|---|
a) | The word "a" |
[[:alpha:]]) | One letter |
???) | Exactly three characters |
*.txt) | Words that end with .txt |
*) | Anything (put it last as the default) |
#!/bin/bash
read -p "enter word > "
case "$REPLY" in
[[:alpha:]]) echo "is a single alphabetic character." ;;
[ABC][0-9]) echo "is A, B, or C followed by a digit." ;;
???) echo "is three characters long." ;;
*.txt) echo "is a word ending in '.txt'" ;;
*) echo "is something else." ;;
esacCombine patterns with |
| joins several patterns for the same commands. Good for upper and lower case answers.
case "$REPLY" in
q|Q) echo "Program terminated."
exit
;;
a|A) echo "Hostname: $HOSTNAME"
uptime
;;
yes|y|Y) echo "Confirmed." ;;
*) echo "Invalid entry" >&2
exit 1
;;
esacAt work
case is the standard way to read options and sub-commands: start|stop|restart|status) in service scripts.
Run more than one match with ;;&
Normally case stops after the first match. With ;;& instead of ;;, it also tests the next patterns.
#!/bin/bash
read -n 1 -p "Type a character > "
echo
case "$REPLY" in
[[:upper:]]) echo "'$REPLY' is upper case." ;;&
[[:lower:]]) echo "'$REPLY' is lower case." ;;&
[[:alpha:]]) echo "'$REPLY' is alphabetic." ;;&
[[:digit:]]) echo "'$REPLY' is a digit." ;;&
[[:graph:]]) echo "'$REPLY' is a visible character." ;;&
[[:punct:]]) echo "'$REPLY' is a punctuation symbol." ;;&
[[:space:]]) echo "'$REPLY' is a whitespace character." ;;&
[[:xdigit:]]) echo "'$REPLY' is a hexadecimal digit." ;;&
esaccase4-2
Type a character > a
'a' is lower case.
'a' is alphabetic.
'a' is a visible character.
'a' is a hexadecimal digit.Summary of the chapter
case word in pattern) … ;; esac replaces long if chains; | joins patterns; *) is the default; ;;& keeps testing.
1Which pattern catches every value that no other pattern matched?
*), written as the last pattern.
2How do you accept both "q" and "Q" in one pattern?
q|Q).
3What is the difference between ;; and ;;&?
;; stops after the match; ;;& also tests the following patterns.