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?
Also consider /sys (sysfs), e.g. /sys/class/net/<device name>/...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With