I am trying to create a simple bash script that tells the user to enter a char. The user only has a limited number of possible options to enter. If he enters the correct one out of the options allotted, then that option is then returned back from the function. If not, then the user is asked to enter a correct option.
Here is the script I wrote:
#receive from the user an input and verify that it is a valid option. If not, try again.
#input1: The number of valid options
#input2: array of valid inputs (can be single characters or strings).
# EXAMPLE:
# ARRAY=("a" "b")
# ReceiveValidInput 2 "${ARRAY[@]}" # there are TWO valid options. Valid options are ${ARR[0]}="a", ${ARR[1]}="b"
function ReceiveValidInput()
{
echo "testing"
InputNum=$1 #get the first input1
shift # Shift all arguments to the left (original $1 gets lost)
ARRin=("$@") #get the second input2 in the form of an array
ProperInputFlag="false"
while [[ "$ProperInputFlag" == "false" ]]; do
echo "enter input and then press enter"
read UserInput
index=0
while [[ $index < $InputNum ]]; do
if [[ "${ARRin[index]}" == "$UserInput" ]]; then
echo $UserInput #we do echo because this is how it is returned back (see https://stackoverflow.com/a/17336953/4441211)
ProperInputFlag="true" #this will cause the while loop to break and exit the function
fi
index=$((index+1))
done
if [[ "$ProperInputFlag" == "false" ]]; then
echo "Invalid input. Please enter one of these options:"
index=0
while [[ $index < $InputNum ]]; do
echo "Option1 $((index+1)): " ${ARRin[index]}
index=$((index+1))
done
fi
done
}
I use the function this way:
ARRAY=("a" "b")
testing=$(ReceiveValidInput 2 "${ARRAY[@]}")
echo "Received: "$testing
read -p "press enter to exit"
exit 1
And it does not work. This syntax testing=$(ReceiveValidInput 2 "${ARRAY[@]}")
simply causes the script to get stuck and nothing happens.
However, if I run ReceiveValidInput 2 "${ARRAY[@]}"
then the function gets called and everything work except I don't get to capture the "return" value.
Any idea how to write the syntax correctly for calling the function so that I can obtain the "return" value which is technically echoed back?