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}}==
This example uses [[Bash]] with its [http://www.softpanorama.org/Scripting/Shellorama/Control_structures/select_statements.shtml select] statement, but Bash did not invent this feature. The ''select'' loop comes originally from the [[Korn Shell]], and appears in some other shells.

{{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 "$@".
if [[ -n $CHOICE ]]; then
break
else
echo Invalid choice.
fi
done
}


PS3='Which is from the three pigs: '
This example uses bash shell with its [http://www.softpanorama.org/Scripting/Shellorama/Control_structures/select_statements.shtml select] statement. This example also works with other shells, such as [[pdksh]], that provide the select statement.
choose 'fee fie' 'huff and puff' 'mirror mirror' 'tick tock'
[[ -n $CHOICE ]] && echo You chose: $CHOICE
[[ -z $CHOICE ]] && echo No input.</lang>


<pre>$ bash menu.sh
<lang bash>bash$ PS3='Which is from the three pigs: '
bash$ select phrase in 'fee fie' 'huff and puff' 'mirror mirror' 'tick tock'; do
> if [[ -n $phrase ]]; then
> PHRASE=$phrase
> echo PHRASE is $PHRASE
> break
> else
> echo 'invalid.'
> fi
> done
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
PHRASE is huff and puff
You chose: huff and puff</pre>
bash$</lang>


{{omit from|GUISS}}
{{omit from|GUISS}}