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.
More on find, xargs, jq and yq
What are the most useful `find` predicates for operations work?BeginnerWhat is the difference between `-exec cmd {} \;`, `-exec cmd {} +` and `-delete`?IntermediateHow does `find` evaluate `-o` (OR) and why do you need parentheses?AdvancedWhat does `xargs` do, and which flags matter?IntermediateWhy is `find | xargs rm` dangerous and what is the safe form?IntermediateWhat is `jq` and what are the filters you use every day?Beginner