bash

What quotes are correct in this bash echo use case?


I have the following snippet:

RESPONSE=$(curl ...)
FILTERED=$("echo '$RESPONSE' | jq '.[]' | jq -r '.name' | head -1")

I can't find the correct syntax to make it work and not introduce a security risk through command injection, in case the curl request returns malicious data.

echo '{"key":"value"}' | jq '.[]' | jq -r '.name' | head -1: command not found

I ensured the commands jq and head are available on the system.

I tried several approaches:

FILTERED=$("echo \"$RESPONSE\" | jq '.[]' | jq -r '.name' | head -1")
FILTERED=$("$RESPONSE | jq '.[]' | jq -r '.name' | head -1")

Solution

  • You only need double quotes around $RESPONSE, to expand it. You can also simplify your jq usage:

    FILTERED=$(echo "$RESPONSE" | jq -r '.[0].name')