Thursday, March 13, 2014

Add time stamp to a file name from CLI

I often find myself in need to append a time stamp to a file name, but always forget the right command line parameters. Here's a quick reminder to myself on how to do just that.

mv filename filename-$(date '+%FT%T')

For those who want to know the details, here's the break down.

Almost all *nix systems have the date command, which can print or set system date and time. Simply type date and current date and time are displayed:

Mon Aug 19 20:37:57 WIT 2013

By default, the date is printed in a "human friendly" form. Unfortunately, it's long, contains spaces, which need escaping and doesn't sort well. A more useful format would look like so: 2013-08-19T20:37:57. This format is also known as ISO 8601 standard.

We can specify the output format by passing it to date command like so:

date '+%Y-%m-%dT%H:%M:%S'

Or if you're using a relatively modern *nix distribution like so:

date '+%FT%T'

To append current time stamp to a file name, run:

mv filename filename-$(date '+%FT%T')

To create a new file with current time stamp in its name, run:

touch filename-$(date '+%FT%T')