0

I ran into an issue where bc does not have boolean expressions in the AIX system. Wondering if there is a replacement command so I don't have make my code any longer? This is in a bash script.

Here is what I had:

percent=-0.17
max=0.20
if [[ $(bc <<< "$percent <= $max && $percent >= -$max") -ge 1 ]]; then
    echo "Under the $max acceptable buffer: File ACCEPTED" 
else
    echo "Over the $max acceptable buffer: File REJECTED"
    exit 1
fi

This is my output:

++ bc
syntax error on line 1 stdin
+ [[ '' -ge 1 ]]
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Tags
  • 3

1 Answers1

3

bc's POSIX spec does not require bare conditionals, and AIX's bc does not support them. You would have to break out the test like this:

percent=-0.17
max=0.20
if [[ $(bc <<< "if ($percent <= $max) if ($percent >= -$max) 1") -eq 1 ]]; then
    echo "Under the $max acceptable buffer: File ACCEPTED" 
else
    echo "Over the $max acceptable buffer: File REJECTED"
    exit 1
fi

Re-formatting the bc script, it looks like this:

if ($percent <= $max) 
  if ($percent >= -$max) 
    1

... only if the $percent value is within both ranges does the expression 1 get executed, which prints 1 to stdout.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • I see what you did here. But if floats are working in the if statements this should work by just comparing the two numbers directly? – Tags Sep 17 '18 at 20:04
  • @Tags, bash arithmetic is integer-only at this point; ksh93 supports floating point. See also: https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks. So you need to be careful with the shell, or use a utility that supports it. – Jeff Schaller Sep 17 '18 at 20:10
  • I see. Thanks and this works perfectly. I just didnt like that a null is passed but that was an easy modification – Tags Sep 17 '18 at 20:17