Switch statement for bash script
Hello, i am currently trying out the switch statement using bash script.
CODE: showmenu () { echo "1. Number1" echo "2. Number2" echo "3. Number3" echo "4. All" echo "5. Quit" } while true do showmenu read choice echo "Enter a choice:" case "$choice" in "1") echo "Number One" ;; "2") echo "Number Two" ;; "3") echo "Number Three" ;; "4") echo "Number One, Two, Three" ;; "5") echo "Program Exited" exit 0 ;; *) echo "Please enter number ONLY ranging from 1-5!" ;; esac done OUTPUT: 1. Number1 2. Number2 3. Number3 4. All 5. Quit Enter a choice: So, when the code is run, a menu with option 1-5 will be shown, then the user will be asked to enter a choice and finally an output is shown. But it is possible if the user want to enter multiple choices. For example, user enter choice "1" and "3", so the output will be "Number One" and "Number Three". Any idea? |
put "|" . eg 1|3) echo "1 or 3" ;;
|
Just something to get you started.
Code:
#! /bin/bash |
Ok will try it out first. Thanks.
|
This can be done just by wrapping your case block in a for loop and changing one line.
Code:
#!/bin/bash Cheers, EVo2. |
Thanks people!
|
Hi all, i am currently trying out this code.
CODE: showmenu () { echo "1. Number1" echo "2. Number2" echo "3. Number3" echo "4. All" echo "5. Quit" } while true do showmenu echo "Enter a choice (1-5):" read choices clear echo -e '\E[034;1m'"\033[1mSunOS Audit ...\033[0m" for choice in $choices do case "$choice" in 1) #clear echo "Number One" ;; 2) #clear echo "Number Two" ;; 3) #clear echo "Number Three" ;; 4) #clear echo "Number One, Two, Three" ;; 5) #clear echo -e '\E[031;1m'"\033[1mPROGRAM CLOSED!\033[0m" exit 0 ;; *) echo "INVALID INPUT! PLEASE TRY AGAIN!" ;; esac done echo -e '\E[034;1m'"\033[1mSCAN COMPLETED\033[0m" exit 0 done RUN: 1. Number1 2. Number2 3. Number3 4. All 5. Quit Enter a choice (1-5): 1 32 2 When the code is run, the user will be prompt to enter the choices he or she wants. So right now, i enter the choices "1 32 2". But however choice "32" is actually invalid, so the output will be this: OUTPUT: SunOS Audit ... Number One INVALID INPUT! PLEASE TRY AGAIN! Number Two SCAN COMPLETED Is it possible that if an invalid choice is being catch, the script will immediately prompt the user to re-enter the choice again? Any idea? |
Yes, use "break" to jump out of the for loop, which will send control back to the top of the while loop
Code:
*) |
All times are GMT -5. The time now is 04:06 AM. |