Select, Case in if-else statement requires double inputs
I need to find out where is the problem. I need to write a script that prompts users to make Yes/No choice in if/else statement. In general I have a bash script that runs like this
if CONDITION; then
COMMANDS1
else
COMMANDS2
echo "Does this look okay to you? (WARNING: This action will not be recoverable!) :
PS3="Select a number: "
select yn in "Yes" "No"
do
case $yn in
"Yes" )
echo "Ok!" ; break ;;
"No" )
echo "Aborted!" ; break ;;
esac
done
fi
But when I run the script, it shows
Does this look okay to you? (WARNING: This action will not be recoverable!)
1) Yes
2) No
Select a number: (I have to press anything here)
Select a number: (Only this input does something).
I ran the script with sh -vx and it shows that it runs both select and case separately. How do I make sure I only need one input?
+ echo 'Does this look okay to you? (WARNING: This action will not be recoverable!) : '
Does this look okay to you? (WARNING: This action will not be recoverable!) :
+ PS3='Select a number: '
+ select yn in '"Yes"' '"No"'
1) Yes
2) No
Select a number: 1
+ case "$yn" in
Select a number: 2
+ case "$yn" in
+ echo 'Aborted!'
Aborted!
+ break
Thank you very much!
EDIT: I am running bash on Mac OS 14.1.
Works for me. I suspect there is text remaining in stdin
from some previous input, to which you are adding some input, and (crucially) a newline.
You could add a *
default case, and print what is stored in REPLY
. I would probably want to show that in visible form, to identify what is pending:
( * ) printf '%s' "${REPLY}" | od -A n -t x1ac;;
I would also quote "$yn"
, as I am unsure what case
would do with multiple words here.