2

I was going through old tutorials and I found one shell script:

a=10
b=20
if  $a -eq $b 
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi

When I stored this shell script as test.sh and executed it. It gives me below output

test.sh: 3: test.sh: 10: not found
a is not equal to b

I don't understand the first line of the output. I would appreciate if anyone can throw light on what's going on.

1
  • 1
    The Internet is full of incompetent shell scripting tutorials. Find a different one. The Stack Overflow bash tag wiki has a reading list, though it is understandably geared towards Bash, not sh. Many things work the same, anyway, and a good tutorial should explain the differences, and teach you both portable shell programming and Bash specifics. Commented Mar 4, 2016 at 20:50

1 Answer 1

2

The if expects a test, like this: [ $a -eq $b ] or [[ $a -eq $b ]].

Your sample expands to: if 10 -eq 20 at which point bash looks for a program called 10 which obviously doesn't exist, hence the error message.

A missing program apparently evaluates as false which leads to the execution of the else statement.

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

2 Comments

When Bash tries to execute a program that doesn't exist, it returns an exit status of 127. Like all non-zero exit codes, this is considered by the shell to be false.
if does not expect a test; it just expects a valid command. test (and its unfortunate alias [) is just one such valid command, albeit the one the OP wants.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.