Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape quotes in jq

Tags:

bash

shell

jq

I've the following two bash lines

TMPFILE="$(mktemp)" || exit 1

< package.json jq '. + {"foo":'"${BOO}"'}' > "$TMPFILE"

but I get the following error:

jq: error: syntax error, unexpected '}' (Unix shell quoting issues?) at <top-level>, line 1:
. + {"foo":}
jq: 1 compile error

any idea how to escape properly that part by having the double quote there to mute the shellcheck error

like image 460
Mazzy Avatar asked Jun 13 '17 08:06

Mazzy


1 Answers

Just use a variable and save yourself the hassle:

< package.json jq --arg b "$BOO" '. + { foo: $b }'

--arg b "$BOO" creates a variable $b that you can use inside jq, without having to deal with quoting issues.

That said, the reason that your attempt was failing was that you were missing some literal double quotes:

< package.json jq '. + { foo: "'"$BOO"'" }'

The extra double quotes inside each of the the single-quoted parts of the command are needed, as the other ones are consumed by the shell before the command string is passed to jq.

This will still fail in the case that the shell variable contains any quotes, so the first approach is the preferred one.

like image 155
Tom Fenech Avatar answered Nov 18 '22 23:11

Tom Fenech