brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: jq --arg passes a variable from your script into a jq filter without quoting trouble

Jq
~/tips/tip-shell-jq-arg-variables

NAME="web 1"

Hands shell variables to jq safely, as strings or as real JSON values.

The first thing everyone tries is gluing a shell variable into the jq filter with double quotes. That breaks as soon as the value has a quote or a space in it, and the escaping turns ugly fast.

jq has a cleaner way. --arg defines a variable you can use inside the filter:

NAME="web 1"
docker inspect $(docker ps -q) | jq --arg name "/$NAME" '.[] | select(.Name == $name) | .State.Status'

The filter stays in single quotes, the value comes in separately, and $name holds exactly what you passed, so you never have to escape anything.

Caveat, and it is in the manual too: the value is always a string. --arg n 5 gives you "5", so a comparison like .count > $n compares against text and gives the wrong answer. For numbers, booleans or a whole object use --argjson:

jq --argjson min 100 '.[] | select(.size > $min)' files.json

The value of --argjson must be valid JSON, so a plain word like hello fails there. That is the main thing I’d keep in mind when choosing between the two.

All named arguments are also in $ARGS.named, which helps when a script passes several of them and you want to print them as one object for debugging.

Further reading: jq manual: invoking jq, On this site: jq select() filters JSON by a field value, On this site: jq -r prints strings without the quotes

More Jq tips jq -r '.files[] | @sh' data.json jq -n -c 'limit(3; range(1; 1000000000))' jq -n -c '$ARGS.positional' --args a "b c" jq 'with_entries(.key |= ascii_upcase)' jq '.replicas |= . + 1' deploy.json All Jq tips (20) All topics

Link