Erroruploading
Erroruploading

Reputation: 27

Why is my arithmetic condition evaluated as true?

I have a sample logic. By calculation, it is -2 > 0 . This is a false condition and I get no result, but I am getting the value as abcd.

#!/bin/bash
Val1=1
Val2=1
Val3=2
Name=abcd
log=/tmp/log
if [ "$((Val1-(Val2 + Val3))) -ge 0" ] ; then echo "$Name"  | tee -a "$log"; fi

I have verified on ShellCheck, and it is giving me this message. I couldn't get how to fix this?

$ shellcheck myscript
 
Line 7:
if [ "$((Val1-(Val2 + Val3))) -ge 0" ] ; then echo "$Name"  | tee -a "$log"; fi
                             ^-- SC2157: Argument to implicit -n is always true due to literal strings.

Upvotes: 0

Views: 81

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52152

If you use [ 'a string' ], that's the same as [ -n 'a string' ]: it checks if the parameter is non-empty. You're providing the argument "$((Val1-(Val2 + Va3))) -ge 0", which evaluates to the string "-2 -ge 0". "Implicit -n" means that the shell really checks

if [ -n "-2 -ge 0" ]

and that is always true, because that's not an empty string.

The reason is your quoting. This would work instead:

if [ "$((Val1-(Val2 + Val3)))" -ge 0 ]

Strictly speaking, the quotes aren't necessary, but they don't hurt, either.

Or, since you're using Bash, you could use an arithmetic conditional:

if ((Val1 - (Val2 + Val3) > 0))

Upvotes: 1

Erroruploading
Erroruploading

Reputation: 27

I figured after posting the question

#!/bin/bash
Val1=1
Val2=1
Val3=2
Name=abcd
log=/tmp/log
if [ "$((Val1-(Val2 + Val3)))" -ge 0 ] ; then echo "$Name"  | tee -a "$log"; fi

Upvotes: 0

Related Questions