Home > Blockchain >  Prefix every line of bash script output with time since script start
Prefix every line of bash script output with time since script start

Time:05-15

Main question in the title: I want to prefix every line of script output with time since start of the script.

Background. I use GNU parallel to run jobs, some of which produce output (most of them don't). I want to prepend each task's output line with time since that task started.

CodePudding user response:

You could add a line into the top of your bash script like this:

#!/bin/bash

exec > >(trap "" INT TERM; while read line ; do printf "%d: %s\n" $SECONDS "$line"; done )

for ((i=0;i<10;i  )) ; do
  sleep 1
  echo hello
done

If you want milliseconds since start, you could do something like this:

#!/bin/bash

exec > >(trap "" INT TERM; start=$(date  %s%N); while read line ; do now=$(date  %s%N); ((ms=(now-start)/1000000)); printf "%d: %s\n" $ms "$line"; done )

for ((i=0;i<10;i  )) ; do
  sleep 1
  echo hello
done
  • Related