21

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

jww
  • 97,681
  • 90
  • 411
  • 885
tonymx227
  • 5,293
  • 16
  • 48
  • 91

2 Answers2

31

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 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 ` – datapug Sep 17 '21 at 15:41
  • Thank you, it's fixed now. – chepner Sep 17 '21 at 16:59
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.

Aaron
  • 24,009
  • 2
  • 33
  • 57