if
commands to identify which of the possible choices had been selected. This type of construct appears frequently in programs, so much so that many programming languages (including the shell) provide a flow-control mechanism for multiple-choice decisions., we see the logic used to act on a user’s selection shows some valid patterns.Table 31-1. case Pattern Examples
Pattern | Description |
---|---|
| Matches if |
| Matches if |
| Matches if |
| Matches if |
| Matches any value of |
Here is an example of patterns at work:
#!/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." ;; esac
It is also possible to combine multiple patterns using the vertical pipe character as a separator. This creates an “or” conditional pattern. This is useful for such things as handling both upper- and lowercase characters. For example:
#!/bin/bash # case-menu: a menu driven system information program clear echo " Please Select:A.
Display System InformationB.
Display Disk SpaceC.
Display Home Space UtilizationQ.
Quit " read -p "Enter selection[A, B, C or Q]
> " case $REPLY inq|Q)
echo "Program terminated." exit ;;a|A)
echo "Hostname: $HOSTNAME" uptime ;;b|B)
df -h ;;c|C)
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 ;; esac
Here, we modify the case-menu
program to use letters instead of digits for menu selection. Notice that the new patterns allow for entry of both upper- and lowercase letters.