0

I m writing shell program to compare two numbers and show the status using test command

#!/bin/sh
a="42"
b="23"
echo $a
test [$a -eq $b]
echo $?

but I m getting error like this eq: line 5: test: [42: integer expression expected 2

1

6 Answers 6

3

You have to change the line

test [$a -eq $b]

to

test $a -eq $b  

test expects an integer expression and [$a -eq $b] is not an integer expression.

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

1 Comment

and maybe a few explanatory words ... ? ;)
1

You have to use one because they are the same (regardless of some shell builtins)

$ ls -l /bin/{test,[}
-rwxr-xr-x  1 root  wheel  22704  4 May 00:05 /bin/[
-rwxr-xr-x  1 root  wheel  22704  4 May 00:05 /bin/test

so either

test expr

or

[ expr ]

or even

/bin/[ expr ]

Comments

0

Loose the square brackets. from

test [$a -eq $b]

Where line should be

test $a -eq $b

Comments

0

Use below simplified answer

#!/bin/sh
a=42
b=23
echo $a
test $a -eq $b
echo $?

It will print answer as 1 since a is not equal to b

Comments

0

Please remove the square brackets.

From the manual pages, you use the square brackets as an alternate to explicitly using the "test" word. So it is one or the other.

From the man page:

test Evaluate a conditional expression expr. Syntax
      test expr
         [ expr ]
        [[ expr ]] [ is a synonym for test but requires a final argument of ].

Comments

0

Try man test and in the manual page you will see that it expects your expression after test. Your expression being $a -eq $b, the command should be test $a -eq $b

What you are doing wrong:

  1. Using square brackets is as same as the test. Try man [ and you will be directed to the same manual page as man test. You are trying to use both
  2. Since [ itself is a command, you need a space after [ before the next part of the command. Therefore it should be [ $a -eq $b ] instead of [$a -eq $b]

In the line where you have used test [$a -eq $b], you can use either

  1. test $a -eq $b or
  2. [ $a -eq $b ]

Comments

Your Answer

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