niefpaarschoenen
niefpaarschoenen

Reputation: 570

stdout all at once instead of line by line

I wrote a script that gets load and mem information for a list of servers by ssh'ing to each server. However, since there are around 20 servers, it's not very efficient to wait for the script to end. That's why I thought it might be interesting to make a crontab that writes the output of the script to a file, so all I need to do is cat this file whenever I need to know load and mem information for the 20 servers. However, when I cat this file during the execution of the crontab it will give me incomplete information. That's because the output of my script is written line by line to the file instead of all at once at termination. I wonder what needs to be done to make this work...

My crontab:

* * * * * (date;~/bin/RUP_ssh) &> ~/bin/RUP.out

My bash script (RUP_ssh):

for comp in `cat ~/bin/servers`; do
    ssh $comp ~/bin/ca
done

Thanks,

niefpaarschoenen

Upvotes: 1

Views: 216

Answers (2)

eff
eff

Reputation: 417

Assuming there is a string to identify which host the mem/load data has come from you can update your txt file as each result comes in. Asuming the data block is one line long you could use

for comp in `cat ~/bin/servers`; do
    output=$( ssh $comp ~/bin/ca )
    # remove old mem/load data for $comp from RUP.out
    sed -i '/'"$comp"'/d' RUP.out # this assumes that the string "$comp" is
                                  # integrated into the output from ca, and
                                  # not elsewhere
    echo "$output" >> RUP.out
done

This can be adapted depending on the output of ca. There is lots of help on sed across the net.

Upvotes: 0

Joakim Nohlgård
Joakim Nohlgård

Reputation: 1852

You can buffer the output to a temporary file and then output all at once like this:

outputbuffer=`mktemp` # Create a new temporary file, usually in /tmp/
trap "rm '$outputbuffer'" EXIT # Remove the temporary file if we exit early.
for comp in `cat ~/bin/servers`; do
    ssh $comp ~/bin/ca >> "$outputbuffer" # gather info to buffer file
done
cat "$outputbuffer" # print buffer to stdout
# rm "$outputbuffer" # delete temporary file, not necessary when using trap

Upvotes: 2

Related Questions