There are a few issues in your code. The immediate issue causing you your present problem is that you are using the wrong syntax. To save the output of a command or a pipeline of commands in a variable, you likely want to use a command substitution, variable=$(some command)
.
A second issue is your use of $TEST
unquoted. When the variable expansion is unquoted, the shell will split its value on spaces, tabs, and newlines (the contents of the IFS
variable), and then apply filename globbing to each of the split-up bits. This means that a JSON document like {"foo": "a * bar"}
may end up outputted together with all the visible filenames in the current directory.
Yet another issue is your use of echo
to output variable data. If the JSON document contained a string with an encoded tab (\t
) or newline (\n
), then the echo
may cause these to be expanded to literal tabs and newlines. The following question with answers talks more in-depth about this: Why is printf better than echo?
Since you want to pass your JSON document from a shell variable to a jq
expression to extract the value of the top-level foo
key, we may do this like so:
document='{"foo": "bar"}'
signature=$( jq -n -r --argjson data "$document" '$data.foo' )
This creates a jq
variable called data
containing the JSON structure found in the document
shell variable. The jq
command then extracts the foo
key's value from this without reading any data from any file or data stream (since -n
is used). The extracted string is decoded (since -r
is used) and stored in the shell variable signature
.
To output the value of the signature
variable:
printf '%s\n' "$signature"
... but if all you wanted to do was to output the value, then there is no point in first storing it in a shell variable. Instead, you would let jq
output the value directly by omitting the command substitution:
document='{"foo": "bar"}'
jq -n -r --argjson data "$document" '$data.foo'
echo "$TEST"
– glenn jackman Jul 02 '15 at 19:01echo
may translate things like\n
or\t
to literal newlines and tabs, which would break when it arrives atjq
. It's better to useprintf
. – Kusalananda Aug 24 '22 at 22:40