Using dictionaries in shell scripts

Sometimes you need to script in bash. And it’ll probably be a pain in the neck. Dictionaries to the rescue!

Anyway, chances are that, if you have ever written some scripts, you have already come up with something like this:

Bash doesn’t allow returning two values so we need to return a string which represents multidimensional data, using ; as delimiter.

Can we do better?

I think so!

With a set of scripts such as this one, we can write:

We’re using textual data to represent a dictionary/map in this case.

The script isn’t smaller, but that’s not our main objective. We’re trying to achieve legibility.

If you only read cut -d';' -f1 you have no idea what's going on unless you debug the code. If you read dict::get foo at least you can expect it to return something foo-like.

Also, it composes very nicely:

There are more examples here.

Why not JSON? Or YAML?

If you’re sure that the platform which will run the script has something like jq then JSON is a good candidate!

But if you want the script to be extremely portable, then a custom solution is required. Besides, the core of the library has ~30 lines of code, anyway.

This post first appeared on Medium.