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 --args puts extra command line words into $ARGS.positional

Jq
~/tips/tip-jq-args-positional

jq -n -c '$ARGS.positional' --args a "b c"

Passes any number of values from the shell to a jq filter as an array.

--arg passes one named value. When a script has a whole list, naming each one is silly. jq can take the rest of the command line as an array.

jq -n -c '$ARGS.positional' --args a "b c"
["a","b c"]

Everything after --args becomes a string in $ARGS.positional, and quoting is respected, so "b c" stays one item. Use --jsonargs when the values should be parsed as JSON:

jq -n -c '$ARGS.positional' --jsonargs 1 true '{"a":2}'
[1,true,{"a":2}]

That makes it easy to build JSON in a shell script from a list the user typed, without gluing strings together. A filter like .[] | select(.id as $i | $ARGS.positional | index($i | tostring)) then picks records by a list of ids.

The caveat is that, after --args, jq reads the remaining words as values and no longer as file names. Put your input file before it (jq '.x, $ARGS.positional' x.json --args a b works) or feed the data on stdin. Without any words after the flag, the array is empty.

The named values live in the same object. With jq -n -c '$ARGS.named' --arg k v you get {"k":"v"}, and jq -n -c '$ARGS' --args a b prints {"positional":["a","b"],"named":{}}. So one variable holds both kinds, and {ids:$ARGS.positional} builds an object around the list.

Further reading: jq manual

More Jq tips jq -r '.files[] | @sh' data.json jq -n -c 'limit(3; range(1; 1000000000))' jq 'with_entries(.key |= ascii_upcase)' jq '.replicas |= . + 1' deploy.json cut -d: -f1,7 /etc/passwd | jq -R 'split(":") | {user: .[0], shell: .[1]}' All Jq tips (20) All topics

Link