0

I would like to modify a json file using JQ in a Bash script. Here is what I tried to proceed:

var="test-54342"
echo "$( jq '.context["customer-name"] = "$var"' cdk.json )" > cdk.json

I also tried this but it's not working as well:

var="test-54342"
echo `$( jq '.context["customer-name"] = "$var"' cdk.json )` > cdk.json

Here is what my json file looks like:

{
  "app": "mySuperApp",
  "context": {
    "customer-name": "text-I-want-to-modify"
  }
}

Sébastien Serre
  • 374
  • 1
  • 6
  • 17
  • See `jq --arg`, as described in existing Q&A – Charles Duffy Nov 05 '21 at 19:17
  • BTW, don't use `echo "$(somecommand)" >file`; just run `somecommand >file` – Charles Duffy Nov 05 '21 at 19:18
  • Also, redirecting output to the same file you're trying to read from doesn't work. See: [How can I use a file in a command and redirect output to the same file without truncating it?](https://stackoverflow.com/questions/6696842/how-can-i-use-a-file-in-a-command-and-redirect-output-to-the-same-file-without-t) – Gordon Davisson Nov 05 '21 at 19:20
  • Ahh, _that's_ why the OP is using the `echo "$(...)"` hack. Not that it's a reliable workaround for the bug (because redirections run before the commands they apply to start, whether the input will still be available to read is undefined), but it explains the intent. – Charles Duffy Nov 05 '21 at 19:23
  • Yep, I found this hack to avoid using another temp variable. So how can I pass a variable in the `echo` command? – Sébastien Serre Nov 05 '21 at 19:44
  • 1
    @SébastienSerre Use `jq --arg`, as Charles said and the linked duplicate explains in more detail. – Gordon Davisson Nov 07 '21 at 20:24

0 Answers0