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's $ENV reads environment variables straight into a filter

Jq
~/tips/tip-jq-env-variables

export SITE=example.com RETRIES=3

Pull values from environment variables into jq output without passing them as arguments.

When a script already has its settings in environment variables, jq can read them itself through $ENV. I find that cleaner than a long row of arguments.

export SITE=example.com RETRIES=3
jq -n '{site: $ENV.SITE, retries: ($ENV.RETRIES | tonumber)}'
# {"site": "example.com", "retries": 3}

$ENV is an object holding every environment variable of the jq process, and $ENV.SITE picks one out. Because the value never goes through shell quoting inside the filter, spaces, quotes and dollar signs in it can’t break your jq program. -n starts with no input, which is what you want when you’re building JSON from scratch, for example a body for curl.

There’s also env, which does the same thing. I prefer $ENV because it reads like the variables you pass with --arg.

Two things to watch. Environment variables are always strings, so numbers and booleans need tonumber or a comparison like == "true", as I did with RETRIES. And jq only sees exported variables: a plain SITE=example.com on its own line in a script isn’t passed to child processes, so $ENV.SITE comes back as null without any error. Put the variable on the same line as the command, or export it.

Further reading: jq manual: $ENV, env

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