Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write JSON file using Bash?

Tags:

linux

bash

pm2

I'd like to write a JSON file using BASH but it seem's not working well..

My code :

sudo echo -e "Name of your app?\n"
sudo read appname
sudo cat "{apps:[{name:\"${appname}\",script:\"./cms/bin/www\",watch:false}]}" > process.json

Issue : -bash: process.json: Permission denied

like image 716
tonymx227 Avatar asked Oct 06 '16 12:10

tonymx227


People also ask

Does Bash support JSON?

Unfortunately, shells such as Bash can't interpret and work with JSON directly. This means that working with JSON via the command line can be cumbersome, involving text manipulation using a combination of tools such as sed and grep.

What is jq in Bash?

The jq command-line tool is is a lightweight and flexible command-line JSON processor. It is great for parsing JSON output in BASH. One of the great things about jq is that it is written in portable C, and it has zero runtime dependencies.


2 Answers

To output text, use echo rather than cat (which outputs data from files or streams).

Aside from that, you will also have to escape the double-quotes inside your text if you want them to appear in the result.

echo -e "Name of your app?\n"
read appname
echo "{apps:[{name:\"${appname}\",script:\"./cms/bin/www\",watch:false}]}" > process.json

If you need to process more than just a simple line, I second @chepner's suggestion to use a JSON tool such as jq.

Your -bash: process.json: Permission denied comes from the fact you cannot write to the process.json file. If the file does not exist, check that your user has write permissions on the directory. If it exists, check that your user has write permissions on the file.

like image 178
Aaron Avatar answered Oct 13 '22 21:10

Aaron


Generally speaking, don't do this. Use a tool that already knows how to quote values correctly, like jq:

jq -n --arg appname "$appname" '{apps: [ {name: $appname, script: "./cms/bin/www", watch: false}]}' > process.json

That said, your immediate issues is that sudo only applies the command, not the redirection. One workaround is to use tee to write to the file instead.

echo '{...}' | sudo tee process.json > /dev/null
like image 23
chepner Avatar answered Oct 13 '22 21:10

chepner