1

So I have this little problem. I'm not sure where it went wrong because I'm pretty sure I got the code right. Here's the code:

#!/bin/bash
playerHP=100
echo "Hello World"
echo "HP: $playerHP"
echo "Continue? (Y/N):"
read -p $confirm
if [ "$confirm" = "y" ]
then
    echo "Yes"
elif [ "$confirm" = "n" ]
then
    echo "No"
else
    echo "No such command"
fi

Here's the result: enter image description here

3
  • 1
    shellcheck.net will point you to the problem Commented Apr 5, 2018 at 14:55
  • 1
    The code you post in your question is different from the code in the error message. Hint: missing quotes. Commented Apr 5, 2018 at 14:56
  • The code you posted does not conform to the code you are running. You posted [ "$confirm" = "n" ] (good!), but the error message implies [ $confirm == "n" ] (bad). Commented Apr 5, 2018 at 14:58

2 Answers 2

5

Unrelated: read needs a prompt after -p. Blend the previous echo into it, and while at it, remove the $ from the variable name there.

read -p "Continue? (Y/N):" confirm

The error message is confusing. Don't you have MSWin line ends in the script?

Sign up to request clarification or add additional context in comments.

2 Comments

It's more than "while at it" : with the $ the $confirm variable is expanded to the empty string before the read builtin is run and the user input is lost.
The rule is that $variablename is used to get the value of the variable; when setting a variable (in an assignment, with read, whatever) just use the plain variable name without the $.
1

Hi I have modified your script below use it. Working fine for me

#!/bin/bash
playerHP=100
echo "Hello World"
echo "HP: $playerHP"
read -p "Continue? (Y/N): " confirm
echo $confirm

if [ "$confirm" = "y" ]
then
    echo "Yes"
elif [ "$confirm" = "n" ]
then
    echo "No"
else
    echo "No such command"
fi

4 Comments

These are the errors I get: ': not a valid identifier: confirm gametest.sh: line 7: $'\r': command not found gametest.sh: line 11: syntax error near unexpected token elif' 'ametest.sh: line 11: `elif [ "$confirm" = "n" ]
can you just execute this line in your command prompt and let me know if [ "y" = "y" ]; then echo "correct"; fi and if [ "y" == "y" ]; then echo "correct"; fi.
gametest.sh: line 7: $'\r'... RC windows?
change this line #!/bin/bash to #!/bin/ksh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.