-1

I am working on a little script that plays a game. At the end, it asks "Play again? [Y/N]" and I would like the game to loop when the user inputs any word starting with 'y'.

My code:

playAgain="yes" while [[ "$playAgain" =~ ^y* ]]; do # working game loop code read -p "Play Again? (y/n): " playAgain done echo "Thank you for playing!" 

at this time the game loop will execute regardless of what is in "playAgain".
Even it I initialize playAgain to "no" the game loop will still execute.
No matter what I type into the "read" call for playAgain, the game loop will execute.

I got the regex syntax from here.

2
  • do you wish to repeat the loop if the user enters a string that begins with a capital Y? Commented Jun 25 at 23:31
  • You mixed 2 different pattern matching syntaxes from superuser.com/q/1056183/1089278 - foo == y* is doing a globbing comparison while foo =~ ^y.* is doing a regexp comparison. It looks like you took the =~ from an answer doing a regexp comparison but the y* from an answer doing a globbing comparison. Globbing and regexps are both used for pattern matching and they look similar but their syntax/metachars (e.g. *) have different meanings. Commented Jun 26 at 10:49

1 Answer 1

6

With the =~ operator, you're using a regular expression. ^ means start of the string, but * means "the previous token repeated zero or more times". You want to say "anything repeated zero or more times" instead, which can be expressed as .* (making the whole expression ^y.*), but you don't need to match the rest of the string: ^y is enough.

[[ $playAgain =~ ^y ]] 

You can use a pattern instead of a regular expression. Then, you need to match the whole string, and * has the same meaning as in path expansion.

[[ $playAgain = y* ]] 

Moreover, you can use parameter expansion, extract the first character only and use direct string comparison.

[[ ${playAgain:0:1} = y ]] # ^ ^ # | | # offset | # length 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.