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: ip -j prints JSON, so jq can pull out an address

Jq
~/tips/tip-networking-ip-j-json-jq

ip -j addr show eth0 | jq -r '.[0].addr_info[] | select(.family=="inet") | .local'

Prints network information as JSON so a script can read an address reliably.

Cutting an IP address out of ip addr with awk breaks the day the output changes a little. The ip tool from iproute2 can print JSON, which is much easier to parse.

Add -j and pipe it into jq:

ip -j addr show eth0 | jq -r '.[0].addr_info[] | select(.family=="inet") | .local'

That prints the IPv4 address of eth0 and nothing else. Swap .local for .prefixlen to get the prefix length. To read the JSON yourself, -p adds indentation:

ip -j -p addr show eth0

The man page says the default JSON is compact and hard to read. The same flag works for other objects, for example ip -j route and ip -j link, so a script can ask for the default gateway without guessing at columns.

Caveats: eth0 is an example, so use the name from ip -br address. The color flag -c is ignored when JSON is on, and the exact set of fields depends on the iproute2 version, so test a script on the machine it will run on.

Further reading: ip(8) manual, jq manual

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