Abdullah Diab’s Blog

Adding a timestamp to command output in linux

This is just a quick solution to put a timestamp with each line of the output of some command in Linux (*nix). It’s a very simple thing, thought I’d write it down here so maybe it’ll help somebody some day.

I have a cron job running on my server, it’s a high frequency job so I don’t want to send email reports each time, I’m logging it into a file, but I want to log the timestamp of each time it runs and logs something to this file, I didn’t want to change the code behind it to also print the timestamp with each write to the output, so I pipelined the command to a simple bash script that will append the timestamp to each line in the output then write the result to the stdout again.

Here is the bash script:

#!/bin/bash
while read x; do
	echo -n `date +%d/%m/%Y\ %H:%M:%S`;
	echo -n " ";
	echo $x;
done

Then I edited the cron job line to be like this:

... /path/to/my/command.sh 2>&1 | /path/to/timestap.sh >> /var/log/cron/my_log.log

And you’re done!

Enjoy it.