Skip to content

Instantly share code, notes, and snippets.

@denisidoro

denisidoro/blog.md Secret

Created Sep 23, 2019
Embed
What would you like to do?

Using dictionaries in bash

Sometimes you need to script in bash. And it'll probably be a pain in the neck.

Anyway, chances are that, if you have ever written some scripts, you have already come up with something like this: https://gist.github.com/5d98ee3cdf10c08c400a399798d4e63c

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: https://gist.github.com/070d7b1ac6cf8676465e4d3f85795b03

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 nice: https://gist.github.com/6843d26ac9ed1fc38333f772844ceda1

You can check 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment