像`ip`这样的工具的输出是用来解析的吗? [英] Is the output of tools like `ip` meant to be parsed?

查看:26
本文介绍了像`ip`这样的工具的输出是用来解析的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,Ubuntu lxc-start-ephemeral bash 脚本执行以下操作来检测正在启动的容器的 IP 地址:

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

我个人不太喜欢这种方法,因为它需要大量摆弄字符串和输出.是否有一个编程 API 来访问相同的信息(不一定在 bash 中),或者它是总是使用 ip 之类的工具的正确方法",并希望您的解析不会中断使用相同工具的其他版本?

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?

推荐答案

在 shell 脚本中,您倾向于通过解析文本来访问数据.这主要是因为 shell 代码只能真正操作字符串,还因为文本比二进制表示更具可移植性.

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.

但是,通常有 UI 命令和 API 命令,shell 脚本应该使用后者而不是前者.例如,您应该调用 stat 而不是尝试解析 ls -l 输出.或者 /proc 中可能有一个文件包含您想要的信息,因此您根本不必运行命令 - 但该文件中的数据仍然是文本形式.

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.

所以,是的 - 当您编写 shell 脚本时,您基本上只能为所有内容解析文本.

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

这篇关于像`ip`这样的工具的输出是用来解析的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆