Learn Bash Scripting by Building Five Programs - Build Five Programs / Fortune Teller

Hello everyone.

I passed all the tests for the fourth Bash program, fortune.sh, and could continue onwards. However, I don’t actually understand why it is working :slight_smile: Any help could be great.

What I don’t understand is why does the code still work even though I call the function before the until loop. I thought it would then have the issue we had earlier in the lesson, where it wouldn’t check that the question asked has a question mark at the end.

#!/bin/bash

# Program to tell a persons fortune

echo -e "\n~~ Fortune Teller ~~\n"

RESPONSES=("Yes" "No" "Maybe" "Outlook good" "Don't count on it" "Ask again later")
N=$(( RANDOM % 6 ))

function GET_FORTUNE() {
  if [[ ! $1 ]]
  then
    echo Ask a yes or no question:
  else
    echo Try again. Make sure it ends with a question mark:
  fi

  read QUESTION
}

GET_FORTUNE

until [[ $QUESTION =~ \?$ ]]
do
  GET_FORTUNE again
done

echo -e "\n$RESPONSES[$N]"

Link to the challenge:

Well there I go again understanding the question after asking it. I see now that the $RESPONSE is at the end, not in the function itself. Hence why using “until” works in this case.

Try investing in a rubber duck. (that’s what they give first year computer science students at Harvard). You are meant to talk to the duck/toy and that will help you work out solutions to problems. (or you can post here. Either way)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.