Adding timestamp to program outputs


#1

Sometimes it is needed to read a program outputs with generated timestamp which you don’t have source code of that program or doesn’t want to make change on code.

How can I add timestamp information on the output text of the programs with a shell function?


#2

You must send program outputs to a pipe, read lines and add timestamp before the text.

Here is an example function:

adddate() {
    while IFS= read -r line; do
	printf "\033[1;31m%s\033[0m %s\n" "$(date +%s.%N)" "$line"
    done
}

You can copy this function into ~/.bashrc or any other file read on login.

Example usage:

$ grep root /etc/passwd | adddate
1459093897.771286856 root:x:0:0:root:/root:/bin/bash

Prefix part consist of unixtimestamp.nanoseconds.

If you don’t want to make colorful prefix, replace printf line as below:

printf "%s %s\n" "$(date +%s.%N)" "$line"