LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   How to invoke the calculator "bc" in bash script for floating point arithmetic? (http://www.linuxquestions.org/questions/programming-9/how-to-invoke-the-calculator-bc-in-bash-script-for-floating-point-arithmetic-808084/)

bluesmodular 05-15-2010 10:42 PM

How to invoke the calculator "bc" in bash script for floating point arithmetic?
 
Hello,

My main problem right now is doing floating point arithmetic within a bash script, with variables.

Right now I have a folder called "myExamples" with a script called "run_example" that runs with no issues.

I plan to
(1) create many folders inside [myExamples], that are named [example10] [example11]...
each containing an identical copy of (run_example),
(2) modify Line 172 of each copy of (run_example)...
in one copy, it would be 3.00, the next copy would have 3.05, etc. (This part doesn't work!)

How can I use the available calculator bc code to do floating point operations?
Thank you for your help!


My code is below -

#!/bin/sh

# run from directory where this script is
cd `echo $0 | sed 's/\(.*\)\/.*/\1/'` # extract pathname

# Make many folders containing executables of slightly different parameters...
for i in `seq 10 11`;
do
mkdir examples$i
done

# Copy the same file into all the folders where (run_example) and [examples{num}] are in ~/myExamples
for i in `ls -d */`;
do cp run_example "$i";
done;

# Replace... something... in (run_example) for each folder
bulksize=`expr 6.00`
half=$(( bulksize / 2)) # THIS LINE DOES NOT WORK

for i in `ls -d */`;
do
cat $i/run_example | sed -e '172 s/[0-9]*/\$half/' > $i/run_example # THIS LINE DOES NOT WORK
half=`expr $half + 0.05`; # THIS LINE DOES NOT WORK
done;



When I replaced
half=$(( bulksize / 2))
with
half=$bulksize/2 | bc

I got
expr: non-numeric argument

bluesmodular 05-15-2010 11:38 PM

[SOLVED] ... invoke the calculator "bc" in bash script for floating point arithmetic?
 
Actually I just solved it -
half=$(echo "scale=2; $bulksize / 2" | bc)
half=$(echo "scale=2; $half + 0.05" | bc)

grail 05-16-2010 12:58 AM

Please mark as SOLVED using the thread tools so everyone else knows too :)


All times are GMT -5. The time now is 05:24 AM.