0

I am trying to use the simple conditional if statement as follows

    val=-148.32
    con=4.0
    if [ $val > $con ]
    then
    echo 'akash'
    else
    echo 'mondal'
    fi

in the above case I should get the output as mondal but I'm getting always akash. Can anyone plz let me know what mistake I'm doing?

Thank you.

  • Are the '\' actually in your script? As in all of that is actually one line with no semicolons ? – John3136 May 31 '22 at 07:27
  • See https://stackoverflow.com/a/52859683/171318 – hek2mgl May 31 '22 at 07:27
  • [Bash only deals in integers](https://stackoverflow.com/a/12722107/60281). You will need [`bc`](https://linux.die.net/man/1/bc) if you want to work on float values. -- I assume the backslashes are some kind of artifact, as the script will not work at all with them in place. I'd also suggest you look into the more robust `[[ ]]` bash builtin instead of `test` / `[ ]`. – DevSolar May 31 '22 at 07:32
  • Yes yes those backslashes are not present in the actual script. And thank you for providing the link. I have found the way from the link. – Akash Mondal May 31 '22 at 08:52

2 Answers2

0

The immediate problem is that a few of those backslashes are syntax errors.

The proper way to write this would be

val=-148.32
con=4.0
if [ $val -gt $con ]
then
  echo 'akash'
else
  echo 'mondal'
fi

though if you really wanted to, you could rewrite it as

val=-148.32;\
con=4.0;\
if [ $val -gt $con ];\
then\
  echo 'akash';\
else\
  echo 'mondal';\
fi

The ; separators are equivalent to newlines as statement separators (and the backslashes escape the actualy newline) -- as you can see, the separator is optional after then and else (but not before).

The > operator is supported by the [ (aka test) command, but it performs strict string comparison. The numeric comparison for greater-than is -gt.

The indentation is not syntactically important, but omitting it makes your code rather unreadable for human consumers.

However, as others have already remarked, Bash does not have any support for floating-point arithmetic. If you can rephrase your problem into an integer one, you should be able to use e.g.

val=-148.32
con=4.00
if [ ${val/.//} -gt ${con/.//} ]; then
    echo 'akash'
else
    echo 'mondal'
fi

but this requires the number of decimal points to be fixed, or at least predictable.

A common workaround is to use Awk instead.

val=-148.32
con=4.0
awk -v c="$con" '{ if ($1 > c) print "akash"; else print "mondal" }' <<<"$val"
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

I overcome the barrier in the following way

    if awk "BEGIN {exit !($val > $con)}"
    then
    statement
    else
    statement
    fi

where $val and $con are real variable