Tech Support > Operating Systems > Linux / Variants > Addition within bash script
Addition within bash script
Posted by Chiefy on March 6th, 2004


How do I go about adding, within a bash script, numbers grepped from a log?

I'm using the following to extract connect times from syslog:

#!/bin/bash
LOG=/var/log/syslog
BACK=1
OUT=/tmp/test-out.log
cat $LOG | grep "Connect time" | sed 's/ / 0/g' | \
grep "`date --date="$BACK days ago" '+%h %d'`" | cut -d" " -f8 >> $OUT

How can the output digits be added together?.

Posted by Nick Landsberg on March 6th, 2004




Chiefy wrote:

use awk

--
Ñ
"It is impossible to make anything foolproof because fools are so
ingenious" - A. Bloch


Posted by P.T. Breuer on March 6th, 2004


Chiefy <lgb@non.existent.invalid> wrote:
Write a shell function that sums a series of numbers.



Hint:

sum() {
local tot=0
while ... ; do
let tot+=$(( $item ))
done
echo $tot
}

I leave the rest to you ..

Peter

Posted by Chris F.A. Johnson on March 6th, 2004


On Sat, 06 Mar 2004 at 18:19 GMT, Chiefy wrote:
Unnecessary use of cat; use the filename as an argument to grep:

grep "Connect time" $LOG | sed 's/ / 0/g' | \

Why not just (not tested; there are no "Connect time" records in my
syslog):

total=0
yesterday=`date -d "-${BACK}days "+%h %_d"`
grep "Connect time.*$yesterday" | {
while read a b c d e f g num junk
do
total=$(( $total + $num ))
done
echo $total
}

The shell can do arithmetic.

--
Chris F.A. Johnson http://cfaj.freeshell.org/shell
================================================== =================
My code (if any) in this post is copyright 2004, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License

Posted by Chris F.A. Johnson on March 6th, 2004


On Sat, 06 Mar 2004 at 19:50 GMT, Chris F.A. Johnson wrote:
That should be:

grep "Connect time.*$yesterday" $LOG | {

Or:

grep "Connect time.*`date -d "-${BACK}days "+%h %_d"`" $LOG |
awk '{total += $8} END {print total}

--
Chris F.A. Johnson http://cfaj.freeshell.org/shell
================================================== =================
My code (if any) in this post is copyright 2004, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License


Similar Posts