Bogudan
Bogudan

Reputation: 121

Prefix every line of bash script output with time since script start

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.

Upvotes: 3

Views: 388

Answers (2)

Ole Tange
Ole Tange

Reputation: 33740

Try:

parallel --lb --tagstring '{= $job->{start}||=time; $_=time-$job->{start} =}' myjob ::: {1..100}

Or:

parallel --lb --tagstring '{= $job->{start}||=::now(); $_=::now()-$job->{start} =}' myjob ::: {1..100}

It may not work as expected if you use --retries.

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207728

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

Upvotes: 1

Related Questions