Show elapsed time every second with bash script

I run a shell script in Linux Mint that invokes some processes that take several minutes. For each process, I want to echo as follows:

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 print a new line.

Is there a good way to do this? I just found ways to print the total time at the end, but not the elapsed time when starting the process.

+4
source share
4 answers

Use this at the beginning of your script, this creates a subprocess that runs in the background and continues to update 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 
+8
source

You can run each command over time:

 time <command> 

and then use sed / awk to retrieve elapsed time.

+1
source

You will need to start the process in the background using & , otherwise the rest of the script will wait for it to finish. Use backspaces to overwrite the current line, so make sure you are not using newline characters.

So, to do what you want:

 myproc & myPid=$! # save process id tmp="" while true; do if kill -0 "$myPid"; then # if the process accepts a signal, keep waiting for i in {0..${#tmp}..1}; do printf "%b" "\b" # print backspaces until we have cleared the previous line done tmp=$( printf "Cleaning temp files... %t seconds." ) printf "%s" "$tmp" else break # drop out of the while loop fi sleep 1 done 
+1
source

Here is a way to print awk on STDERR every second. You should simply add:

  • When myprocess is finished, create the file / tmp / SOMETHING
  • Awk has a test: it exits when / tmp / SOMETHING appears

Part of a loop (without completion test ... so there is an "endless loop" to CTRL-C):

  ping 127.0.0.1 | awk ' BEGIN{cmd="date +%s"; cmd|getline startup ; close (cmd) } /bytes from/ { cmd | getline D ; close (cmd) ; print D-startup | "cat >&2" }' 

now you just need to use "printf" and the ansi escape sequence to print without a new line, try ansi-escape to return to the beginning of the number and reset the output (all descriptors) by calling the system:

  ping 127.0.0.1 | awk -v getback4char="$(printf '\033[4D')" ' BEGIN{cmd="date +%s"; cmd|getline startup ; close (cmd) ; printf "Elapsed time: ";} /bytes from/ { cmd | getline D ; close (cmd) ; printf "%4d%s" ,(D-startup) , getback4char | "cat >&2" system("") }' 

note: this is compatible with all versions of awk that I know, even ANCIENT (i.e. not only gawk / nawk, but also venerable awk.)

0
source

Source: https://habr.com/ru/post/1484186/


All Articles