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 @sh quotes values so the shell can use them safely

Jq
~/tips/tip-jq-at-sh-shell-quote

jq -r '.files[] | @sh' data.json

Turns JSON strings into single-quoted shell words that survive spaces and apostrophes.

File names with spaces are where my shell scripts usually fall over, and JSON from an API is full of values I did not choose. Pasting them into a command unquoted is asking for trouble. jq has a formatter that does the quoting for you.

jq -r '.files[] | @sh' data.json

With {"files":["a b.txt","it's.txt"]} the output is two lines:

'a b.txt'
'it'\''s.txt'

Every value is wrapped in single quotes, and a single quote inside the value is escaped the way a shell expects. Give @sh an array and you get all values on one line, separated by spaces:

eval "set -- $(jq -r '.files | @sh' data.json)"
printf '[%s]\n' "$@"

That loads the values into $1, $2 and so on, and the printf shows two items, a b.txt and it's.txt, each intact.

The caveat is the eval. It is only safe because @sh did the quoting, so never build that string by hand. Also remember -r: without it jq wraps the whole result in another pair of double quotes and the shell sees them as part of the text.

Further reading: jq manual

More Jq tips 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 cut -d: -f1,7 /etc/passwd | jq -R 'split(":") | {user: .[0], shell: .[1]}' All Jq tips (20) All topics

Link