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
I really like this method as well, less clutter:
In bash,
Note that bash can only handle integer arithmetic, so if your awk command returns a fraction, then you'll want to redesign: here's your code rewritten a bit to do all math in awk.
I always forget the syntax so I come to google, but then I never find the one I'm familiar with :P. This is the cleanest to me and more true to what I'd expect in other languages.
Another portable
POSIX
compliant way to do inbash
, which can be defined as a function in.bashrc
for all the arithmetic operators of convenience.and just call it in command-line as,
The idea is to use the Input-Field-Separator(IFS), a special variable in
bash
used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator+
.Remember the
IFS
is changed locally and does NOT take effect on the defaultIFS
behaviour outside the function scope. An excerpt from theman bash
page,The
"$(( $* ))"
represents the list of arguments passed to be split by+
and later the sum value is output using theprintf
function. The function can be extended to add scope for other arithmetic operations also.Use the
$(( ))
arithmetic expansion.See http://tldp.org/LDP/abs/html/arithexp.html for more information.