TIL: jq exit code
jq is one of the most common tools I use in shell scripts and ad hoc shell commands. It allows you to parse, and
query JSON data. Personally, I’m on the same page as Kelly Brazil,
modern Unix tools should support both a human-readable text output and a structured text output, so that data can be
safely processed in scripts. He wrote a great blog post back in 2019.
He also wrote the great
jc wrapper, which parses text output and generate structured JSON data from it.
Today, I learned, that
jq can set its exit code depending on the last boolean expression in
jq query. This makes it very easy to write checks like: “Are there 10 infiniband interfaces on my machine?” This is because
iproute2supports JSON based output. The command line for the above question is:
ip -j l | jq -e '.| map(select(.link_type == \"infiniband\")) | length == 10'
This will result in either exit code 1, of there are less or more then 10 infiniband interfaces.
Another powerful query is:
ip -j a | jq '. | .addr_info | select(.scope=="global" and .family=="inet6") | .local'
This gets you all IPv6 addresses on your machine with a global scope.
A note on Yaml and JQ
jq also helps you with processing structured yaml data. With small scripts like yaml2json,
you can convert yaml files to jq back and forth. There is also a tool called
yq out there. Sadly, there are ad least three different implementations, with sligthly different
command line arguements. If you are not in charge of the concrete dependencies, user of a script or Makefile have locally installed, I always use
yaml2json combined with
As there is currently only a single
jq implementation out there.