Home > Net >  Why doesn't my if statement work in shell script?
Why doesn't my if statement work in shell script?

Time:12-04

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!

CodePudding user response:

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 $.

  • Related