Help with Bash shell script

Hi All,

I have a script which as below

#!/bin/bash
for i in `cat servers`
do
ssh uname@$i "df -t xfs --total | grep total";
done > out.txt

Output as below

--------------

total          140583991104 118622795524 21961195580  85% -
total          140583991104 112888595524 27695395580  81% -
total          140583991104 113083933588 27500057516  81% -
total          140583991104 113981125312 26602865792  82% -
total          140583991104 114674546432 25909444672  82% -
total          140583991104 114443785084 26140206020  82% -
total          140583991104 114541732596 26042258508  82% -
total          140583991104 114597880688 25986110416  82% -

----------------

Now I want to extend the script by sum up the columns 2,3 and 4 and average of column 5 and append the output to a file daily in csv format. I did try as below, but not the expected one as i dunno how to include today's date in the script.

#!/bin/bash
for i in `cat servers`
do
ssh uname@$i "df -t xfs --total | grep total";
done | awk '{ sum2 += $2; sum3 += $3; sum4 += $4; sum5 += $5; } END { print sum2/(1024*1024*1024), sum3/(1024*1024*1024), sum4/(1024*1024*1024) , sum5/8 }' > out1.csv

I just need the final output in below format. Please help.

24Jan2018          1047.43 843.116 204.31 81
25Jan2018          1047.43 850.612 196.82 81.9
26Jan2018          1047.43 853.452 193.98 82.12

How about

awk -vDT="$(date +'%d%b%Y')" '
        {sum2 += $2
         sum3 += $3
         sum4 += $4
         sum5 += $5
        }
END     {GIGA=2^30
         print DT, sum2/GIGA, sum3/GIGA, sum4/GIGA , sum5/NR
        }
'

In your $5 summation, your take advantage of awk 's behaviour to take into account leading digits only and to silently drop trailing non-digits (and followers) from a string if used in arithmetics. Please be aware of your uuoc (useless use of cat ) - it's more widely accepted to read a file in a while loop.

1 Like

Thanks Rudic. This helped me. However i just can't figure out how to remove the decimals. I just need the output in numbers without decimals. Can you please help.

Use printf with an appropriate format string.

In case "appropriate format string" isn't obvious, note that it depends on what output you're trying to produce. If you want floating point numbers to be rounded to the nearest integer, use %.0f . If you want floating point numbers to be truncated to the largest integer that is less than or equal to the floating point number, use %d .

For example:

         printf "%s %.0f %.0f %.0f %.0f%%\n", DT, sum2/GIGA, sum3/GIGA, sum4/GIGA , sum5/NR

or:

         printf "%s %d %d %d %d%%\n", DT, sum2/GIGA, sum3/GIGA, sum4/GIGA , sum5/NR
1 Like