Interview Prep/Shell Scripting/find, xargs, jq and yq

How do you pass shell variables into `jq` safely?

IntermediateConceptfind, xargs, jq and yq
Answer

Use --arg (string) and --argjson (JSON value). Never splice variables into the filter text, which breaks on quotes and is an injection risk.

jq --arg ns "$namespace" '.items[] | select(.metadata.namespace == $ns)'
jq --argjson n "$replicas" '.spec.replicas = $n' deploy.json
payload=$(jq -n --arg text "Deploy $version done: $msg" '{text: $text}')   # build JSON
curl -fsS -H 'Content-Type: application/json' --data-binary "$payload" "$SLACK_URL"

Building JSON with jq -n --arg guarantees correct escaping of quotes, backslashes and newlines in commit messages or error output.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on find, xargs, jq and yq