1

So I have a variable that I want to compare with another number in an if statement.

b=8.25
if [ $(echo "$b < 10" | bc) -ne 0 ]; then
echo "hey"
fi

I get the following error

(standard_in) 1: syntax error

I know the issue is having the b variable inside, how can I make it so that I can maintain it in there?

Please help

2
  • 1
    It works for me in Bash. What shell are you using? Commented May 5, 2018 at 19:48
  • You can try b=$'8.25\r';[ ${b%.*} -lt 10 ] && echo "hey" Commented May 5, 2018 at 20:23

2 Answers 2

2

Your script file probably has DOS-style CRLF line endings:

$ b=8.25
$ if [ $(echo "$b < 10" | bc) -ne 0 ]; then
> echo "hey"
> fi
hey

$ b=$'8.25\r'
$ if [ $(echo "$b < 10" | bc) -ne 0 ]; then
> echo "hey"
> fi
(standard_in) 1: illegal character: ^M
bash: [: -ne: unary operator expected

Run dos2unix on your script file.

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

2 Comments

I am using mobaXterm at my school and I don't have permission to run dos2unix, what else can I do?
Those 2 facts have nothing to do with each other. Use sed 's/\r$//'
0

Store the comparison in a variable separateley

b=8.25

# Capture output outside the if
comparison=$(echo  "$b < 10" | bc)

# Use the output in the if
if [ $comparison -ne 0 ]; then

    echo "hey"
fi

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.