0

I wish to check for proper user input as such (pseudo code)

userInput=""

#check until user enters 'y' OR 'Y' OR 'n' OR 'N'

while [[ "$userInput" != "[yYnN]" ]] ; do

     read userInput

done

My idea is to use the [] wild card for matching but what is the proper way to accomplish this task?

theta
  • 179
  • 11
  • Yes. Don't use double quotes around the regexp. Do surround the expression with double brackets. – Mark Plotnick Nov 04 '13 at 01:52
  • @AdamLiss ...well, this one has additional problems (using `[ ]` rather than `[[ ]]`, missing whitespace between the `while` and the test command following). – Charles Duffy Nov 04 '13 at 02:00
  • @theta `[` is a command, not syntax. Like other commands (and much other syntax), it needs to be separated from things that follow it with whitespace. `while [`, not `while[`. And glob matches need `[[ ]]`, not `[ ]`. – Charles Duffy Nov 04 '13 at 02:01

1 Answers1

2

Here's one way:

while true; do
case $userInput in
  y|Y|n|N)
    break
    ;;
  *)
    # read more input
    ;;
esac
done

If you're not concerned with portability, you can use

while [[ ! $userInput =~ [yYnN] ]]; do
Adam Liss
  • 47,594
  • 12
  • 108
  • 150