Mitch Feaver
Mitch Feaver

Reputation: 37

Comparing a negative number in bash script. Unsure what error means

I am trying to compare that an immediate is in bounds and I cannot see why it is not working. Have tried putting the variables in "" still same error and also using (()) with <> as operands. The negative number is -9 and the error I receive is:

./valsplit.sh: line 89: [[: −9: syntax error: invalid arithmetic operator (error token is "??9")

This is my script:

checkImmediate(){
lowerBound=-32768
upperBound=32767
if [[ $immediate -lt $lowerBound || $immediate -gt $upperBound ]]; then
    hasErrors=1
    errors+=("Out of bounds immediate. Immediates range between −32768 and 32767.")
fi
}

I am using OSX.

Any help would be greatly appreciated. Thanks

Upvotes: 0

Views: 922

Answers (2)

that other guy
that other guy

Reputation: 123550

Your syntax is fine, it's your values that are wrong. Here's an example:

$ var='1 –9' # this is a Unicode dash
$ [[ $var -lt 5 ]]
-bash: [[: 1 –9: syntax error: invalid arithmetic operator (error token is "–9")

The value from your posted error has a Unicode dash, and this should be immediately obvious if you look at set -x output.

Ensure that all your variable are integers without special characters. (Note that echo and visual inspection is not enough to determine this since not all characters are printable or distinguishable).

Upvotes: 2

Theofanis
Theofanis

Reputation: 637

As everyone said this is working, for me too (GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16), MacOS Sierra 10.12.4).

Try this

if [ $immediate -lt $lowerBound -o $immediate -gt $upperBound ]; then
    command
fi

Upvotes: 1

Related Questions