0

Trying to figure out the syntax for jq. This line works absolutely fine:

echo $(cat ../post-auth/rkt-auth.json | jq -c --arg user ${vsphere_user} '.credentials.user = $user') > ../post-auth/rkt-auth.json

However this is not the case when variable is a part of json path:

echo $(cat ../post-auth/docker-auth.json | jq -c --arg basejq ${base} --arg tempvarjq ${tempvar} '.auths.$tempvarjq.auth= $basejq') > ../post-auth/docker-auth.json

Error:

jq: error: syntax error, unexpected '$', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.auths.$tempvarjq.auth= $basejq       
jq: 1 compile error

Any suggestions how to correct this syntax with that variable?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Chris
  • 23
  • 6
  • 2
    That's a [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) and a [useless `cat`](/questions/11710552/useless-use-of-cat) btw. – tripleee Jan 14 '19 at 15:54
  • 4
    Also, if your input file is the same as your output file, this is [bound to cause some issues](https://stackoverflow.com/questions/36565295/jq-to-replace-text-directly-on-file-like-sed-i) – Aserre Jan 14 '19 at 15:58
  • 1
    `echo "$(cat file)" >file` isn't guaranteed to do all the reading before it does any writing. Many shells *will* run the command substitution before they run the redirection, but it's not a firm guarantee by the letter of the POSIX standard, and shouldn't be relied on. (Also, even if your shell *does* honor that order-of-operations, it means a failed `cat` run will still invoke `echo`, so your file will be blanked rather than left alone in the event of an error). – Charles Duffy Jan 14 '19 at 16:26

1 Answers1

2

Try this.

jq -c --arg basejq "${base}" \
    --arg tempvarjq "${tempvar}" \
    '.auths[$tempvarjq].auth= $basejq' \
    ../post-auth/docker-auth.json \
        > ../post-auth/docker-auth.json.tmp &&
mv  ../post-auth/docker-auth.json.tmp  \
    ../post-auth/docker-auth.json
peak
  • 105,803
  • 17
  • 152
  • 177
tripleee
  • 175,061
  • 34
  • 275
  • 318