bashmath

bash command line arithmetic echo $((x-y)) how to divide result by z?


I'm trying to figure out a way to take the result of a basic equation and divide by another integer. So in in simple form it looks like; A-B = C and then divide C by D

I understand the first part of the equation is echo $((A-B)) but how do I get that result divided by D?

Any feedback would be greatly appreciated!


Solution

  • Using shell

    This (taken from the comments) fails because the parentheses are unbalanced:

    $ echo $((2147483633-807279114))/5184000))
    

    Try instead:

    $ echo $(( (2147483633-807279114)/5184000 ))
    258
    

    The above returns an integer because the shell only does integer arithmetic.

    Using bc

    If you want accurate floating-point numbers, the standard tool to use is bc:

    $ echo '(2147483633-807279114)/5184000' | bc -l
    258.52710628858024691358
    

    Using python

    Python supports both integer and floating point arithmetic:

    $ python3 -c 'print ((2147483633-807279114)//5184000)'
    258
    $ python3 -c 'print ((2147483633-807279114)/5184000.0)'
    258.527106289
    

    Python, with its numpy extension, is an excellent tool even if your needs extend to complex scientific calculations.

    Using awk

    awk, a standard unix tool, supports floating-point math:

    $ awk 'BEGIN{print (2147483633-807279114)/5184000;quit}'
    258.527