Arithmetic operation in bash script, multiply by decimal number, how?

GNU bash, version 5.1.8(1)

How can i please do this in a bash script, i want to multiply certain number by decimal number 1.5

Non working attempts:

result=$(( $number * 1.5 |bc -l ))
                    ^---------------^ SC2004: $/${} is unnecessary on arithmetic variables.
                                        ^-^ SC2079: (( )) doesn't support decimals. Use bc or awk.
                                             ^-- SC2154: bc is referenced but not assigned (for output from commands, use "$(bc ...)" ).
                                                 ^-- SC2154: l is referenced but not assigned.
result=$(( $number * 1,5 ))
                    ^---------------^ SC2004: $/${} is unnecessary on arithmetic variables.
#!/bin/bash
number=3456
result=$( echo "$number*1.5"|bc )
echo "$result"

output is decimal (5184.0) which i do not want, i want whole numbers only result

Impossible with Bash alone (at least directly), which frankly is very stupid. Anything else is necessary for that.

The easiest I know (I dunno awk or something) is with Python:

python -c 'import sys;print(int(eval(" ".join(_i for _i in sys.argv[1:] if _i))))'

For ex:

$ python -c 'import sys;print(int(eval(" ".join(_i for _i in sys.argv[1:] if _i))))' '2.2*2.2'
4
$ python -c 'import sys;print(int(eval(" ".join(_i for _i in sys.argv[1:] if _i))))' '2.2' '*2.2'
4

I wasn’t able to quickly find how to pipe instead.

1 Like

Thanks, here are some other possible ways:

result=$(echo "10*1.5/1" | bc )
echo "$result"

result=$( awk "BEGIN { print int(10*1.5)}" )
echo "$result"

result=$((10*3/2))
echo "$result"

result=$((number+number/2))
echo $result

You can set number of digits after decimal point using the scale=0; option when standard math library used using the -l option:

echo "scale=0; 10*1.5/1" | bc -l

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki