Refactor for simplicity and dependencies

Posted on: by

A couple of weeks ago, Dr. Drang, a blogger you should really read, posted a note about his process for setting up directories for the new year. He files things by year and month. He prefers the month to be zero padded. Here is the way he explained how he does it.

mkdir 2017
cd 2017
jot -w %02d 12 | xargs mkdir

When I read this I admired the fact that he put in the effort to automate this, but this process bothered me a little.

My first issue with Dr. Drang’s solution was that it uses four separate commands across three lines to accomplish. My second issue was the use of the jot command. Jot is a great utility except for the fact that it doesn’t ship preinstalled on Linux. It does ship preinstalled on FreeBSD and macOS.

I am always looking for ways to eliminate dependencies and this command is full of them. I recalled that mkdir had a -p option which creates intermediary directories if they do not exist, so I thought if we could stick to Bash, a common shell, and utilities that come preinstalled on most *nix’s that would be better so I came up with this:

mkdir -p $(printf "2017/%02i " $(seq 1 12))

Feeling clever, I decided to email Dr. Drang and see if he had thought about refactoring and eliminating a couple of the dependencies. We exchanged a couple of emails and his basic response was that he only uses macOS and he was already familiar with the jot command. He also indicated he was not a fan of the $() Bash syntax. Fair enough. He even wrote another post to discuss things further, it seems I wasn’t the only one that emailed him other solutions. This was his new solution:

jot -w 2017/%02d 12 | xargs mkdir -p

Certainly more compact, but it still doesn’t seem like the most elegant solution to me. After giving it some more thought, my original solution wasn’t very elegant either. I decided to consider using brace expansion in Bash. So I came up with a solution that is both more compact and something that appears more elegant:

mkdir -p 2017/{01..12}

This solution eliminates all other commands besides the use of mkdir and the only dependency is Bash. I am not sure a solution exists that could be more compact than this but if anyone knows of one let me know.