Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.
#!/bin/bash
echo "Int. a number"
read num1
echo "Int. another numer"
read num2
if ["$num1"="$num2"]; then
echo "Equals"
else
echo "Dif"
fi
if["$num1"<0]; then
echo "The number $num1 is negative"
else if ["$num2"<0]; then
echo "The number $num2 is negative"
fi
#

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

thanks

share|improve this question

3 Answers 3

up vote 5 down vote accepted

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.

share|improve this answer
3  
-eq, -ne, -lt, -gt, -le, -ge. see the bash manpage, section "Conditional Expressions" –  quack quixote May 30 '10 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.

s="b"
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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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