Bash – Appending data to file with a single open/close from a shell script

bashshell

I need to adjust my shell script and write to $log multiple times. Opening and closing the file repeatedly will cause an increase in runtime.

How can I write everything at once to the file, including all echo statements defined in my script?

#!/bin/sh
log="loadlog.log"

for i in {1..10}
do
   n=$((100*$i))
   echo "## Users=$i  requests=$n ##" >> $log     
   ab -n $n -c $i  http://mainserver.com/index.html  >>  $log
   ssh root@mainserver cat /proc/loadavg >> $log
   echo "======" >> $log
done

Best Answer

I’m not sure, but I guess you want to open the log file for writing just once, do you?

If so, you need to use a sub-shell, output to the STDOUT and, outside, send it to the log file.

#! /bin/bash
log="loadlog.log"

(
for i in {1..10}; do
    n=$((100*$i))

    echo "## Users=$i  requests=$n ##"

    ab -n $n -c $i  http://mainserver.com/index.html

    ssh root@mainserver cat /proc/loadavg

    echo "======"
done
) >> $log

As well, I recommend you to do something with your code-style—it’s unreadable. And, you need to use #!/bin/bash because you use bash-specific constructs in the loop.