I've written a menu driven bash script that uses a switch case
inside of a while
loop to perform the various menu options. Everything works just fine. Now I'm trying to improve the program by performing error testing on the user input, but I cannot seem to make it work...
The problem is I don't know how to properly break out of a switch statement, without breaking out of the while loop (so the user can try again).
# repeat command line indefinitely until user quits
while [ "$done" != "true" ]
do
# display menu options to user
echo "Command Menu" # I cut out the menu options for brevity....
# prompt user to enter command
echo "Please select a letter:"
read option
# switch case for menu commands, accept both upper and lower case
case "$option" in
# sample case statement
a|A) echo "Choose a month"
read monthVal
if [ "$monthVal" -lt 13 ]
then
cal "$monthVal"
else
break # THIS DOES NOT WORK. BREAKS WHILE LOOP, NOT SWITCH!
fi
;;
q|Q) done="true" #ends while loop
;;
*) echo "Invalid option, choose again..."
;;
esac
done
exit 0
The program works fine when the user enters a valid month value, but if they enter a number higher than 13, instead of breaking the switch statement and repeating the loop again, the program breaks both the switch and while loop and stops running.
One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.
Here is how you can detach a process from bash shell. If a given process is running in the foreground, press Ctrl+z to interrupt it.
What is an exit code in bash shell? Every Linux or Unix command executed by the shell script or user has an exit status. Exit status is an integer number. 0 exit status means the command was successful without any errors.
This should do the trick: Wrap the code in a one-trip for-loop:
#! /bin/bash
case foo in
bar)
echo "Should never get here."
;;
foo)
for just in this_once ; do
echo "Top half only."
if ! test foo = bar; then break; fi
echo "Bottom half -- should never get here."
done
;;
*)
echo "Should never get here either."
;;
esac
I think what you mean to do with break
is "quit this case statement and restart the while loop". However, case ... esac
isn't a control-flow statement (although it may smell like one), and doesn't pay attention to break
.
Try changing break
into continue
, which will send control back to the start of the while loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With