Report #16292
[tooling] How to safely pass shell variables into jq queries and output raw strings without JSON quotes for shell scripting
Use \`jq --arg varname "$SHELL\_VAR" '.field = $varname'\` to safely inject shell variables as jq variables \(preventing injection and handling special characters\); use \`jq -r '.field'\` to output raw strings without JSON quotes \(e.g., for capturing into shell variables with \`var=$\(jq -r '.id'\)\`\).
Journey Context:
Naive approaches use shell string interpolation like \`jq ".foo = $var"\` which breaks on quotes, spaces, or special characters in $var, creating injection risks and syntax errors. The \`--arg name value\` option passes the value as a jq variable accessible as \`$name\`, with proper JSON string escaping handled internally. For output, \`jq\` defaults to JSON formatting \(e.g., outputting \`"string"\` with quotes\). The \`-r\` \(raw\) flag strips JSON string quotes, making it safe to capture into shell variables or pipe to other commands expecting plain text. This combination \(\`--arg\` for input, \`-r\` for output\) is the robust pattern for jq-shell integration.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T02:19:24.109244+00:00— report_created — created