How to loop back to original select menu from a case within a case statement?

I have the following bash script called q.txt. I want to run a select statement with a case statement. How can I re-display the menu options after a) case has been run. . /home/chh1/q.txt won't run after echo "a" in case a).

It is clear to me why this does not work but is there a way to loop back to the original select menu after a case has been executed?

#!/bin/bash
select x in a b c d
do
case $x in a) echo "a" . /home/chh1/q.txt;; b) echo "b";; c) echo "c";; d) echo "You are now exiting the program" break;; *) echo "Invalid entry. Please try an option on display";;
esac
done
2

1 Answer

You can add an outer loop driven by a variable.

#!/bin/bash
anew=yes
while [ "$anew" = yes ]; do anew=no select x in a b c d do case $x in a) echo "a" anew=yes break;; b) echo "b";; c) echo "c";; d) echo "You are now exiting the program" break;; *) echo "Invalid entry. Please try an option on display";; esac done
done

The initial anew=yes makes the while loop execute at least once. Inside the loop the variable is set to no, then a slightly modified version of your select loop is executed. The idea is: when the script exits the select loop, the variable should be either yes or no, and the body of the while loop should be repeated or not, respectively. The case a simply sets the variable to yes and breaks the select loop.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like