Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the output of tools like `ip` meant to be parsed?

For example, the Ubuntu lxc-start-ephemeral bash script does the following to detect the IP address of a container that is 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 really like this approach, as it requires a lot of fiddling around with strings and outputs. Is there a programmatic API to access the same information (not necessarily in bash), or is it 'the right way' to always shell out to tools like ip, and hope that your parsing won't break with other versions of the same tool?

like image 230
sokrates Avatar asked Oct 14 '25 12:10

sokrates


2 Answers

Also consider /sys (sysfs), e.g. /sys/class/net/<device name>/...

like image 84
Robert Siemer Avatar answered Oct 17 '25 02:10

Robert Siemer


In shell scripting, you tend to get access to data by parsing text. This is largely because shell code can only really manipulate strings, but also because text is more portable than binary representations.

As a rule, however, there are UI commands and API commands, and shell scripts should use the latter instead of the former. For instance, you should call stat instead of trying to parse ls -l output. Or there may be a file in /proc containing the information you want so you don't have to run a command at all - but the data in that file will still be in text form.

So, yeah - when you write shell scripts, you're basically stuck parsing text for everything.

like image 27
Mark Reed Avatar answered Oct 17 '25 02:10

Mark Reed