23

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

5
  • 1
    have you checked you have permission to create a file at specified location ? Commented Oct 6, 2016 at 12:28
  • 1
    sudo echo and sudo read on the first two lines look completely pointless to me Commented Oct 6, 2016 at 12:29
  • When I do sudo vim process.json it works... Commented Oct 6, 2016 at 12:30
  • vim opens the file; with > process.json, the shell opens the file before sudo actually runs. Commented Oct 6, 2016 at 12:32
  • Possible duplicate of Output JSON from Bash script Commented Jun 22, 2019 at 18:19

2 Answers 2

34

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
Sign up to request clarification or add additional context in comments.

2 Comments

Cannot make it an edit because that requires at least 6 characters, but the backtick after false}]} should be replaced with standard tick to work properly: jq -n --arg appname "$appname" '{apps: [ {name: $appname, script: "./cms/bin/www", watch: false}]}' > process.json
Thank you, it's fixed now.
12

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.

2 Comments

Is there a tutorial for this?
@NoelHarris for what exactly? jq, bash, quoting in bash?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.