Is the output of tools like `ip` meant for analysis?

For example, the Ubuntu lxc-start-ephemeral

bash script does the following to discover the IP address of the container being launched:

# Grab all the public globally routed IPv4 and IPv6 addresses
(sudo ip netns exec $NAME ip -4 addr show scope global && \
 sudo ip netns exec $NAME ip -6 addr show scope global) | grep inet | while read line; do
    ip=$(echo $line | awk '{print $2}' | cut -d '/' -f1)
    echo "$ip"
done

      

I personally don't like this approach as it takes a lot of effort with lines and exits. Is there a software API to access the same information (not necessarily in bash) or is this the "right way" to always lay out tools like ip

, and hope your parsing doesn't break with other versions of the same tool?

+3


source to share


3 answers


In shell scripting, you typically access data by parsing text. This is largely because shell code can actually manipulate strings, but also because text is more portable than binary representations.

However, there are generally UI commands and API commands, and shell scripts should use the latter, not the former. For example, you should call stat

instead of trying to parse the ls -l

output. Or the file /proc

may contain a file containing the information you want, so you don't need to run the command at all, but the data in that file will still be in text form.



So yes, when you write shell scripts you basically get stuck on parsing text for everything.

+1


source


Also consider /sys

(sysfs) for example./sys/class/net/<device name>/...



+2


source


Using the Proc Filesystem

If you just need another way to parse your IP address, you can parse /proc/net/arp

directly. You will still have to parse the data you want, but the data format should only change if / when the proc filesystem is changed by the Linux kernel. This seems stable enough for most purposes, IMHO.

0


source







All Articles