0

I'm having a small doubt in shell Scripting

I have a program (a.out) which I run several times and it prints a particular value on to the terminal. I need to write a shell script to capture the output of this program and add the outputs.

I wrote the following script

value=0
total=0
for((i=0;i<10;j++)) 
do   
 value=`./a.out $i`
 total=`expr $total + $value`
done
echo value is $value total is $total

Here, I run a.out with an argument being the i values. When I run this script, I get the error expr: non-integer argument

The problem here is with value variable. My a.out gives a double as an output and I need to capture this number in a variable.

I'm a newbie in shell scripting, Can some one please help me on this.

1
  • I think you mean i++, not j++, in the for loop. And ./a.out isn't giving you a double as output; it's giving you a line of text (which you might then store as a string, which might then be interpreted as a number). Commented Aug 9, 2011 at 18:46

2 Answers 2

1

Most shells cannot do floating point arithmetic, but you can call out to bc:

add () { printf "%s + %s\n" $1 $2 | bc -l; }
total=0.0
for ((i=0; i<10; i++)); do
  total=$(add $total $(./a.out $i))
done
Sign up to request clarification or add additional context in comments.

Comments

0

Here are a couple of bash functions for dealing with floating point math: http://www.linuxjournal.com/content/floating-point-math-bash

Look at the example, would be something like:

$tmp_total = $(float_eval "$value + $total")
$total = $tmp_total

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.