bc: using "scale" with bash variable

32,211

Solution 1

Replace single quotes with double; because with single quotes $A in your equation is not expanded, rather considered as literally $A not 12

A=12 ; bc <<< "scale=2;$(($A/5))"
2

Also, inside $(()) to variable does not need to be specified as $A, just A will do, e.g.

A=12 ; bc <<< "scale=2;$((A/5))"
2

Next, when doing $(()) you invoke subshell, which is not what you want to do because bc does not do anything then. Try this

A=12 ; bc <<< "scale=2; $A/5"
2.40

Solution 2

Try with:

A=12;echo 'scale=2;'"$A / 5"|bc -l
Share:
32,211

Related videos on Youtube

watchmansky
Author by

watchmansky

Updated on September 18, 2022

Comments

  • watchmansky
    watchmansky over 1 year

    Easily, I'm writing a script that needs some values with 2 digits after floating point. Trying to use bc I don't understand how use "scale", i.e.

    A=12 ; bc <<< $(($A/5))
    

    it's correct, but adding "scale" leads to an error:

    A=12 ; bc <<< 'scale=2;$(($A/5))'
    
    (standard_in) 1: illegal character: $
    (standard_in) 1: illegal character: $