tags:

views:

97

answers:

3

How do I run 100 iterations using a bash shell script? I want to know how long will it take to execute one command (start and end time). I want to keep track which iteration is currently running. I want to log each iteration. I have one automated script I need to run and log it.

for i in 1 2 3
do
    command1
done

But I want to know how long it takes to complete one iteration - and write the information to a log file too!

+2  A: 
for ((i = 1; i <= 100; i++)); do
    echo "--- Iteration #$i: $(date) ---"
    time command1
done 2>&1 | tee timing.log

There's a lot going on here. What's happening?

  1. The for loop iterates from 1 to 100 using C-style syntax.
  2. The $i in the echo printout prints the current iteration number.
  3. $(date) inserts a timestamp into each printout.
  4. The time command runs a command and prints how long it took to execute.
  5. The output from everything inside of the loop is piped to tee, which saves a copy to timing.log.
  6. The 2>&1 redirects stderr to stdout so that the log file will contain both regular output and error messages.
John Kugelman
A: 

The following script shows one way to do it.

#!/usr/bin/bash
for i in {1..100} ; do
    echo =============================
    echo "Number $i: $(date +%Y-%m-%d-%H:%M:%S)"
    ( time ( echo $i ; sleep 1 ) ) 2>&1 | sed 's/^/   /'
done | tee timing.log

It uses the bash range feature to run 100 iterations of the loop, outputting the loop counter and date.

It then times your command (echo $i ; sleep 1 in this case) and combines standard output and error before nicely formatting it, and sending it to both the terminal and a log file for later analysis.

A smaple run with five iterations:

pax> testprog.sh
=============================
Number 1: 2010-09-16-13:44:19
   1
   real 0m1.063s
   user 0m0.077s
   sys  0m0.015s
=============================
Number 2: 2010-09-16-13:44:20
   2
   real 0m1.056s
   user 0m0.030s
   sys  0m0.046s
=============================
Number 3: 2010-09-16-13:44:21
   3
   real 0m1.057s
   user 0m0.046s
   sys  0m0.030s
=============================
Number 4: 2010-09-16-13:44:22
   4
   real 0m1.057s
   user 0m0.061s
   sys  0m0.031s
=============================
Number 5: 2010-09-16-13:44:23
   5
   real 0m1.057s
   user 0m0.046s
   sys  0m0.015s
paxdiablo
A: 

You may use seq in interation as well:

for i in `seq 1 100`; do ... done

Gadolin