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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With