Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shell script for 100 iterations and log time taken

Tags:

bash

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!

like image 731
user449122 Avatar asked Sep 16 '10 04:09

user449122


2 Answers

You may use seq in iteration as well:

for i in `seq 1 100`; do ... done
like image 56
Gadolin Avatar answered Sep 28 '22 18:09

Gadolin


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.
like image 45
John Kugelman Avatar answered Sep 28 '22 16:09

John Kugelman