I have this bash script and I had a problem in line 16. How can I take the previous result of line 15 and add it to the variable in line 16?
#!/bin/bash
num=0
metab=0
for ((i=1; i<=2; i++)); do
for j in `ls output-$i-*`; do
echo "$j"
metab=$(cat $j|grep EndBuffer|awk '{sum+=$2} END { print sum/120}') (line15)
num= $num + $metab (line16)
done
echo "$num"
done
There are a thousand and one ways to do it. Here's one using
dc
:But if that's too bash-y for you (or portability matters) you could say
But maybe you're one of those people who thinks RPN is icky and weird; don't worry!
bc
is here for you:That said, there are a some unrelated improvements you could be making to your script
EDIT:
As described in BASH FAQ 022, bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like
bc
ordc
) is required.In this case the solution would be
To add accumulate possibly-floating-point numbers into
num
.For integers:
Use arithmetic expansion:
$((EXPR))
Using the external
expr
utility. Note that this is only needed for really old systems.For floating point:
Bash doesn't directly support this, but there's a couple of external tools you can use:
You can also use scientific notation (e.g.:
2.5e+2
)Common pitfalls:
When setting a variable, you cannot have whitespace on either side of
=
, otherwise it will force the shell to interpret the first word as the name of the application to run (eg:num=
ornum
)num= 1
num =2
bc
andexpr
expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like3+
+4
.num=`expr $num1+ $num2`
You should declare metab as integer and then use arithmetic evaluation
For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic