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!
You may use
seq
in iteration as well:There's a lot going on here. What's happening?
for
loop iterates from 1 to 100 using C-style syntax.$i
in the echo printout prints the current iteration number.$(date)
inserts a timestamp into each printout.time
command runs a command and prints how long it took to execute.tee
, which saves a copy totiming.log
.2>&1
redirects stderr to stdout so that the log file will contain both regular output and error messages.You can try with:
Explanation
time
time
so we can grep itgrep ^real
is to get only the lines starting with "real" in the output oftime
sed
is to delete the beginning of the line up to minutes part (in the output oftime
)awk
adds to the sum, so that in the end it can output the average, which is the total sum, divided by the number of input records (=NR
)Limitations
The snippet assumes that the running time of some_script.sh is less than 1 minute, otherwise it won't work at all. Depending on your system, the
time
builtin might work differently. Another alternative is to use the time command /usr/bin/time instead of the bash builtin.Note: This script was extracted from here.
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.The following script shows one way to do it.
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: