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.
CodePudding user response:
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"
CodePudding user response:
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