2

I'm working on a simple game that I'm programming in shell for a college assignment and I don't know why my last if doesn't work properly:

#! /bin/bash

sort -n num.txt > sorted_nums.txt

pc_num=`head -1 sorted_nums.txt`

read $user_num

if [ $user_num = $pc_num ]
then
      echo "You are correct"
else
      echo "You're wrong, the right answer was $pc_num"
fi

The problem comes in the if statement because when I run the programme it will always print the error:

./nums.sh: line 9: [: =: binary operator expected

I have also tried replacing = with -eq and still doesn't work

And then print:

You're wrong, the right answer was $pc_num

Thank you!

2
  • 1
    try printing the values of $user_num and $pc_num before the if. To debug programs, it helps to break them into parts and test them independently of each other Commented Dec 3, 2021 at 21:48
  • 1
    Shellcheck identifies several problems with the code. Commented Dec 3, 2021 at 22:36

1 Answer 1

2

Well, you are being directed to the wrong line. Actually you are reading the user input wrong. It must be read user_num without the $.

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

Comments

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.