I don’t know when I started writing a lot of bash scripts. It just seemed to happen over the last few years, possibly because bash is pretty much universally available, even on newly installed Linux systems.
Despite its benefits, one of the things I really hate about bash is
logging. Rolling my own timestamps can be a real PITA, but they’re so
useful that I can’t live without them (optimising software performance
for a living gives you a rather unhealthy obsession with how long things
take). Every script I write ends up using a different timestamp format
because I just can’t seem to remember the
date command I used last.
At least, that was the old me. The new me has discovered the perfect
ts from the moreutils
ts prepends a timestamp to each line it receives on stdin. Adding a
timestamp in your log messages is a simple as:
You can also specify a
strftime(3) compatible format:
But wait, there’s more! If a simple way to print timestamps wasn’t
ts can also parse existing timestamps in the input line (by
ts-tagged logs back into
ts) and preprend an additional
timestamp with cumulative and relative times between consecutive lines.
This is fantastic for answering two questions:
When was a log message printed relative to the start of the program? (
When was a log message printed relative to the previous line? (
-s option tells you how long it took to reach a certain point of
your bash script. And the
-i option helps you which parts of your
script are taking the most time.
Beat that, hand-rolled