common.sh: new function for a selection menu with a default option.

Defined a bash function choose(), which allows to present a menu and
prompting for a selection, with support for default choice. Usage is
commented appropriately.

Originally reviewed in CL I0d2f20dc8d62ce5fa18c10d9f8b51a46b2ddca5d.

BUG=chromium-os:26010
TEST=Tested in conjunction with a use in image_to_usb.sh, works fine.

Change-Id: I53a42a46a3c90fd486fead578bfbae248f64cfc2
Reviewed-on: https://gerrit.chromium.org/gerrit/15586
Reviewed-by: Gilad Arnold <garnold@chromium.org>
Tested-by: Gilad Arnold <garnold@chromium.org>
Commit-Ready: Gilad Arnold <garnold@chromium.org>
This commit is contained in:
Gilad Arnold 2012-02-09 10:19:16 -08:00 committed by Gerrit
parent feb04f77fe
commit 207a7c7e7f

View File

@ -776,3 +776,67 @@ function enable_strict_sudo {
`type -P sudo` -n "$@"
}
}
# Selection menu with a default option: this is similar to bash's select
# built-in, only that in case of an empty selection it'll return the default
# choice. Like select, it uses PS3 as the prompt.
#
# $1: name of variable to be assigned the selected value; it better not be of
# the form choose_foo to avoid conflict with local variables.
# $2: default value to return in case of an empty user entry.
# $3: value to return in case of an invalid choice.
# $...: options for selection.
#
# Usage example:
#
# PS3="Select one [1]: "
# choose reply "foo" "ERROR" "foo" "bar" "foobar"
#
# This will present the following menu and prompt:
#
# 1) foo
# 2) bar
# 3) foobar
# Select one [1]:
#
# The return value will be stored in a variable named 'reply'. If the input is
# 1, 2 or 3, the return value will be "foo", "bar" or "foobar", respectively.
# If it is empty (i.e. the user clicked Enter) it will be "foo". Anything else
# will return "ERROR".
function choose() {
typeset -i choose_i=1
# Retrieve output variable name and default return value.
local choose_reply=$1
local choose_default="$2"
local choose_invalid="$3"
shift 3
# Select a return value
unset REPLY
if [ $# -gt 0 ]; then
# Actual options provided, present a menu and prompt for a choice.
local choose_opt
for choose_opt in "$@"; do
echo "$choose_i) $choose_opt"
choose_i=choose_i+1
done
read -p "$PS3"
fi
# Filter out strings containing non-digits.
if [ "${REPLY}" != "${REPLY%%[!0-9]*}" ]; then
REPLY=0
fi
choose_i="${REPLY}"
if [ $choose_i -ge 1 -a $choose_i -le $# ]; then
# Valid choice, return the corresponding value.
eval ${choose_reply}="${!choose_i}"
elif [ -z "${REPLY}" ]; then
# Empty choice, return default value.
eval ${choose_reply}="${choose_default}"
else
# Invalid choice, return corresponding value.
eval ${choose_reply}="${choose_invalid}"
fi
}