0

I have the following Bash code, which runs a C++ binary (./code) and stores the result:

#!/bin/bash

output=$(./code /);

read -ra arr -d '' <<<"$output" 
value=${arr[-1]}
sum=$value+1.034
echo $sum

I want it to be able to take the value of the variable sum, which is a number less than zero, ie 0.01357 and be able to add another floating point number to it, before outputting the result to the screen.

So the result should be 1.04757, but the output I am currently getting is:

0.01357+1.034
HMLDude
  • 1,547
  • 7
  • 27
  • 47
  • 1
    Bash doesn't support floating point math, plus you're not doing the right thing for math in bash anyways. See https://unix.stackexchange.com/questions/360324/addition-of-two-floating-point-numbers-using-shell-script for ways to get around the lack (they generally involve using `bc` or `awk` or another program) – Shawn Feb 28 '20 at 18:05

1 Answers1

1

Bash doesn't support floating point arithmetics. You need another program doing the math for you.
Here are three examples using bc, awk or GNU datamash:

#!/bin/bash

read -ra arr -d '' <<<"$(./code /)" 

# bc
printf '%s + %s\n' "${arr[-1]}"  "1.034" | bc

# or awk
#awk -v val="${arr[-1]}" 'BEGIN{print val + 1.034}'

# or datamash
#datamash sum 1 <<<$(printf '%s\n' "${arr[-1]}" "1.034")
Freddy
  • 4,548
  • 1
  • 7
  • 17
  • This is quite helpful. Using awk is working for me. I'm curious, if I just wanted to store the result of the sum in a variable, for later use, how would I do that? – HMLDude Feb 28 '20 at 19:26
  • You can use a command substitution: `sum=$(awk -v val="${arr[-1]}" 'BEGIN{print val + 1.034}')` – Freddy Feb 28 '20 at 19:28
  • One more question. What if I had two bash variables that I wanted to add together with awk? – HMLDude Feb 28 '20 at 20:06
  • Assign two variables to `awk` with the `-v` option, e.g. `one="0.5"; two="1.1"; sum=$(awk -v var1="$one" -v var2="$two" 'BEGIN{print var1 + var2}')` or you could `echo` the values and use a pipe like `sum=$(echo "0.5;1.1" | awk -F';' '{ print $1 + $2 }')` – Freddy Feb 28 '20 at 20:14