Prefix stderr redirect with timestamp

2018-05-06 · 1 min read
foo() { while IFS='' read -r line; do echo "$(date) $line" >> file.txt; done; };

It creates a function which reads one line of raw (-r) input from stdin. IFS='' prevents ignoring blank lines. It, then, prepends each line with a timestamp.

Test it

echo 42 > >(foo)

or with tee

echo 42 | tee >(foo)

Subscribe to My Newsletter

The latest programming-related news, articles and resources - sent to your inbox monthly. Unsubscribe anytime.