Interview Prep/Shell Scripting/Troubleshooting: tools, portability, permissions and environment

`jq -r '.[] | select(.name == $svc) | .port' services.json` fails with `jq: error: $svc is not defined at <top-level>, line 1:`.

IntermediateTroubleshootingTroubleshooting: tools, portability, permissions and environment
Answer

Likely causes → Inside single quotes the shell does not expand $svc, so jq sees a jq variable that was never defined. The tempting "fix", switching to double quotes, splices raw shell text into the jq program, which breaks on quotes in the value and allows filter injection.

Diagnose → The error names the undefined jq variable; echo "$svc" confirms the shell has it.

Fix → Pass shell values as jq variables:

jq -r --arg svc "$svc" '.[] | select(.name == $svc) | .port' services.json
jq -n --arg host "$host" --argjson port "$port" '{host: $host, port: $port}'   # building JSON safely

Prevent → Never build jq filters (or JSON bodies) by string interpolation; use --arg, --argjson and --slurpfile.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: tools, portability, permissions and environment