Bash shell script for 100 iterations and log time taken

Viewed 42020

How do I run 100 iterations using a bash shell script? I want to know how long it will 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!

5 Answers

This script is based on the answer from @marian0, but there's no limitation to the running time. Name it timeit.sh and then do ./timeit.sh 10 ./script to run ./script 10 times and print the average time. Additional arguments can be added as desired.

#!/bin/bash

for i in `seq 1 $1`; do
    time "${@:2}"
done 2>&1 |\
    grep ^real |\
    sed -r -e "s/.*real\t([[:digit:]]+)m([[:digit:]]+\.[[:digit:]]+)s/\1 \2/" |\
    awk '{sum += $1 * 60 + $2} END {print sum / NR}'

Related