'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.
Solution 1:[1]
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
Solution 2:[2]
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
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ole Tange |