echo "Int. a number"
read num1
echo "Int. another numer"
read num2
if ["$num1"="$num2"]; then
echo "Equals"
echo "Dif"
if["$num1"<0]; then
echo "The number $num1 is negative"
else if ["$num2"<0]; then
echo "The number $num2 is negative"

this code is not working, i've something wrong when i see if the number is < 0.


3 Answers 3


Wrong syntax. Please read the documentation about the [ command (help [ / help test)

Each argument must be an argument of its own, ie you must use spaces inbetween: [ "$num1" == "$num2" ]. The reason why you don't see an error with the first check is that it tries to find a command named (with num1=3 and num2=4) [3==4], which does not exist, so the expression evaluates to false. At the first check, you wrote a <, which is a shell operator for input redirection. It tries to open the file 4], which in most cases does not exist.

However when comparing numbers, you should use -eq and similar, == is for string comparison: [ 3 == 3.0 ] is false, [ 3 -eq 3.0 ] is true.

  • 3
    -eq, -ne, -lt, -gt, -le, -ge. see the bash manpage, section "Conditional Expressions" May 30, 2010 at 1:29

In Bash, you can do numeric comparisons with the familiar operators if you use arithmetic evaluation:

if ((num1 ==num2 ))

if ((num1<0))    # in this context, < is not evaluated as a redirection operator

else if (( $num2 < 0 ))

As you can see, I've been fairly free with my use of spaces and can omit the dollar sign if I want. You should be aware of this, however:

a=    # set to nothing, thus null
if (( a == 0 )); then echo "ok"; fi    # echoes "ok" since a evaluates to 0
if (( $a == 0 )); then echo "ok"; fi    # produces an error even if $a is quoted

String comparisons can be performed with "<" and ">" instead of "-lt" and "-gt" if you use double square brackets. The requirement for spaces is the same with them as it is for single square brackets.

if [[ "$s" > "a" ]]
t=    # null
if [[ $t < "a" ]]    # evaluates to true

As you can see in the last example, when using double square brackets, it's not necessary to quote variables to protect against the possibility of them being null or unset, unlike when using single square brackets.


The operators you are using do string comparison. You should use -eq for integer equality, -lt for less than, etc (they should also be surrounded by spaces).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.