I want to create a script where I have pre-defined option values. opt1 opt2 opt3
I will start a script and it will ask me to choose from opt1 - opt3. Once I pick e.g. opt2, that opt2 will then be passed as a variable.
How can I please achieve it?
CodePudding user response:
#!/bin/sh
echo "choose an option [ 1 opt1 | 2 opt2 | 3 opt3 ]"
read input
if [ $input == 1 ]
then
output="option 1 was chosen"
elif [ $input == 2 ]
then
output="option 2 was chosen"
elif [ $input == 3 ]
then
output="option 3 was chosen"
else
output="invalid input"
fi
echo "$output"
CodePudding user response:
You can use the "case" command to check if the user value is on a list of expected values:
#!/bin/bash
selected_option=""
echo " *** MENU ***"
echo "1) Opt1"
echo "2) Opt2"
echo "3) Opt3"
echo -n " Please, enter your option: "
read user_answer
case $user_answer in
1|2|3) selected_option="$user_answer"
;;
*) echo "Invalid Option!"
esac
##### Show the result only if the user selected an valid option #####
if [[ ! -z "${selected_option}" ]]; then
echo "Selected Option: [${selected_option}]"
fi
The '|' can be used to separate the valid options, and it will act as an "or" operator.
The '*' section will be executed if the previous condition is not satisfied, which means a "default" behavior, at this case it will display "Invalid Option" message.
Finally, the last if checks if the variable "${selected_option}" is empty, if not it is printed, but you can do whatever you want with that.