Menu: Difference between revisions
Content deleted Content added
No edit summary |
→{{header|UNIX Shell}}: Wrap the select loop inside a new choose() function. This is a quadruple solution for bash, ksh93, pdksh and zsh. |
||
Line 1,354: | Line 1,354: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
⚫ | |||
{{works with|bash}} |
{{works with|bash}} |
||
{{works with|ksh93}} |
|||
{{works with|pdksh}} |
{{works with|pdksh}} |
||
{{works with|zsh}} |
|||
<lang bash># choose 'choice 1' 'choice 2' ... |
|||
# Prints menu to standard error. Prompts with PS3. |
|||
# Reads REPLY from standard input. Sets CHOICE. |
|||
choose() { |
|||
CHOICE= # Default CHOICE is empty string. |
|||
[[ $# -gt 0 ]] || return # Return if "$@" is empty. |
|||
select CHOICE; do # Select from "$@". |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
[[ -n $CHOICE ]] && echo You chose: $CHOICE |
|||
[[ -z $CHOICE ]] && echo No input.</lang> |
|||
<pre>$ bash menu.sh |
|||
⚫ | |||
⚫ | |||
⚫ | |||
> PHRASE=$phrase |
|||
> echo PHRASE is $PHRASE |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
1) fee fie |
1) fee fie |
||
2) huff and puff |
2) huff and puff |
||
Line 1,374: | Line 1,386: | ||
4) tick tock |
4) tick tock |
||
Which is from the three pigs: 5 |
Which is from the three pigs: 5 |
||
Invalid choice. |
|||
invalid. |
|||
Which is from the three pigs: 2 |
|||
You chose: huff and puff |
|||
$</pre> |
|||
Our ''choose'' function wraps a ''select'' loop. This wrapper implements the task requirement to provide an empty string from an empty list of choices. It also breaks the ''select'' loop after the first good choice. A ''select'' loop always continues until the script breaks the loop, or the standard input reaches end of file (EOF). |
|||
If the user enters a blank line, the ''select'' loop repeats the list of choices. This is the only way to print the list again. An invalid choice only repeats the prompt, not the list. |
|||
[[Z Shell]] prints choices in multiple columns. This is good for menus that have many choices. |
|||
<pre>$ zsh scratch.sh |
|||
1) fee fie 2) huff and puff 3) mirror mirror 4) tick tock |
|||
Which is from the three pigs: 2 |
Which is from the three pigs: 2 |
||
You chose: huff and puff</pre> |
|||
bash$</lang> |
|||
{{omit from|GUISS}} |
{{omit from|GUISS}} |