Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show elapsed time every second running a bash script

Tags:

linux

bash

shell

I'm running a shell script in Linux Mint that calls some processes taking few minutes. For each process I want to echo a message like this:

echo "Cleaning temporary files... X seconds."
myprocess

where X is the current elapsed time and I would like it to change every second, but not printing a new line.

Is there a good way to do that? I only found ways to print the total time in the end, but not the elapsed time while running the process.

like image 908
rafa Avatar asked Jun 03 '13 12:06

rafa


People also ask

How do I get elapsed time in bash?

Measure Elapsed Time in Milliseconds in Bash To measure elapsed time with millisecond resolution, use date with +%s. %3N option, which returns the current time in milliseconds.

How does bash calculate execution time?

Using Bash Shell's TIMEFORMAT The TIMEFORMAT is a string format that will be printed after the execution of the block code inside the time{} wrapper finishes. The %R specifies to print the elapsed time in seconds with milliseconds precision. Let's test our script: $ ./elapsed_time.sh It took 12.008 seconds.


2 Answers

Use this at the beginning of your script, this creates a subprocess which runs in background and keeps on updating the status.

file=$(mktemp)
progress() {
  pc=0;
  while [ -e $file ]
    do
      echo -ne "$pc sec\033[0K\r"
      sleep 1
      ((pc++))
    done
}
progress &
#Do all the necessary staff

#now when everything is done
rm -f $file
like image 52
abasu Avatar answered Oct 12 '22 23:10

abasu


You can run each command with time:

time <command>

and then use sed/awk to exctract the elapsed time.

like image 43
Claudio Avatar answered Oct 13 '22 01:10

Claudio