Skip to content
Advertisement

How to populate json file with data from bash variable

I am writing a small bash script and I am stuck. I have a text file with some information and I stored the contents of that file in a bash variable.

JavaScript

My tools.txt file looks like this:

JavaScript

And so on.

What I want is to dynamically create a JSON file named tools.json and to populate that file with the content from tools.txt.

In my tools.json file I have the following structure:

JavaScript

And this should be the final structure.

JavaScript

So the expected output is:

JavaScript

I don’t know how to loop through the $tools variable or tools.txt file in such a way that on each iteration a new line ("docker" : "19.03.8") is added to tools.json file.

I tried something like this

JavaScript

Of course, it doesn’t work. The idea is that instead of "name" : "version" in a loop to use something like "$name" : "$version".

Advertisement

Answer

You can use the tool “jq” for that.

https://stedolan.github.io/jq/manual/

I would do something like this:

JavaScript

A better solution would be:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement