Bash, ksh or zsh provides you with the select
command that is exactly designed to present numbered options menu:
To get the usage of the select
command, type help select
in your bash terminal.
select
: select NAME
[in WORDS
… ;
] do COMMANDS; done
- Select words from a list and execute commands.
- The
WORDS
are expanded, generating a list of words. The set of expanded words is printed on the standard error, each preceded by a number. If in WORDS
is not present, in "$@"
is assumed. The PS3
prompt is then displayed and a line read from the standard input. If the line consists of the number corresponding to one of the displayed words, then NAME
is set to that word. If the line is empty, WORDS
and the prompt are redisplayed. If EOF
is read, the command completes. Any other value read causes NAME
to be set to null
. The line read is saved in the variable REPLY
. COMMANDS
are executed after each selection until a break command is executed.
- Exit Status:
- Returns the status of the last command executed.
Here is an implementation of it with your selection menu:
#!/usr/bin/env bash
choices=('Delete Data' 'Insert Data' 'Get Number of customers' 'Exit')
PS3='Please choose the operation you want: '
select answer in "${choices[@]}"; do
case "$answer" in
"${choices[0]}")
echo 'You have chosen to Delete Data.'
;;
"${choices[1]}")
echo 'You have chosen to Insert Data.'
;;
"${choices[2]}")
echo 'You have chosen to Get number of customers.'
;;
"${choices[3]}")
echo 'You have chosen to Exit.'
break
;;
*)
printf 'Your answer %q is not a valid option!\n' "$REPLY"
;;
esac
done
unset PS3
Another implementation of the select
command, using arguments rather than an array of choices:
#!/usr/bin/env ksh
PS3='Please choose the operation you want: '
set -- 'Delete Data' 'Insert Data' 'Get Number of customers' 'Exit'
select answer; do
case "$answer" in
"$1")
echo 'You have chosen to Delete Data.'
;;
"$2")
echo 'You have chosen to Insert Data.'
;;
"$3")
echo 'You have chosen to Get number of customers.'
;;
"$4")
echo 'You have chosen to Exit.'
break
;;
*)
printf 'Your answer %q is not a valid option!\n' "$REPLY"
;;
esac
done