How to come out of select in Linux
I want to take the input from the user, which could be any of the given options, I tried using select, but it just goes in loop, doesn't come out, is there a way i can make it to come out and proceed after the user has entered right option, here is the sample code:
select envir in "prod" "uat" "dev"; do
开发者_C百科 echo $envir
done
//continue with the script
echo "out of select"
Once user selects any of the available options, it should come out and continue with the scripts, if the user has entered anything else, it should keep on prompting.
From the bash(1) man page:
... The list is executed after each selection until a break command is executed. The exit status of select is the exit status of the last command executed in list, or zero if no commands were exe- cuted. ...
In other words, execute a "break" statement when $envir is nonempty.
select envir in "prod" "uat" "dev"; do
echo $envir
if [ $envir == "prod" ] || [ $envir == "uat" ] || [ $envir == "dev" ]
then
break
fi
done
//continue with the script
echo "out of select"
Thanks Brian. With your input, this is what I was able to do:
select envir in "prod" "uat" "dev"; do
echo $envir
if [ "$envir" != "" ]
then
break
fi
done
//continue with the script
echo "out of select"
I would write the above script this way:
#!/bin/bash
declare -a opts=("prod" "uat" "dev")
echo "control-D to exit"
select envir in "${opts[@]}"; do
echo "envir=$envir"
found=0
for elem in "${opts[@]}"; do
if [ "$elem" = "$envir" ]; then
found=1
break
fi
done
if [ "$found" -eq 1 ]; then
break
fi
done
echo "out of select"
That way your keywords are handled at one place. Every time you add a new word in the list of "prod" "uat" "dev", you don't need to change at 2 places.
You can also read the list of words from an external file and assign that to bash array variable opts here.
精彩评论