捕获bash命令的输出,将其解析并存储到不同的bash变量中 [英] Capture output of a bash command, parse it and store into different bash variables

查看:100
本文介绍了捕获bash命令的输出,将其解析并存储到不同的bash变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:

我有一个很小的 bash 脚本,该脚本只运行 any Linux命令(例如,说ifconfig)

I have a small bash script which simply runs any Linux command (e.g. say ifconfig)

ifconfig 的典型输出如下:

eth0      Link encap:Ethernet  HWaddr 30:F7:0D:6D:34:CA
          inet addr:10.106.145.12  Bcast:10.106.145.255  Mask:255.255.255.0
          inet6 addr: fe80::32f7:dff:fe6d:34ca/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1104666 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2171 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:444437904 (423.8 MiB)  TX bytes:238380 (232.7 KiB)

lo        Link encap:Local Loopback 
          inet addr:127.0.0.1  Mask:255.255.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:15900 errors:0 dropped:0 overruns:0 frame:0
          TX packets:15900 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:467306 (456.3 KiB)  TX bytes:467306 (456.3 KiB)

现在,大多数人通常要做的是将 entire 输出存储到文件/变量中,并根据该结果进行解析.但是我想知道是否我可以将输出的特定部分放在多个变量中(例如,称为${IPETH0} bash变量可以携带IP上例中的 eth0 ${IPLO}的IP地址10.106.145.12携带 lo 的IP地址127.0.0.1,而无需两次运行ifconfig命令 ).

Now what most people usually do is store the entire output into a file/variable and parse based on that. I however want to know if there is anyway that I could put specific parts of the output in more than one variable (say a bash variable called ${IPETH0} to carry the IP address 10.106.145.12 from eth0 and ${IPLO} to carry the IP address 127.0.0.1 from lo in the above example without running ifconfig command twice).

类似于 tee 命令对输入所做的操作,但是我想对 output 执行此操作,并将输出存储到2个或 more 中一口气获得变量.有什么想法吗?

Something like what tee command does with the input but I want to do this for the output and store the output into 2 or more variables in one go. Any ideas?

推荐答案

$ read IPETH0 IPLO <<< $(ifconfig | awk '/inet[[:space:]]/ { print $2 }')
$ echo "${IPETH0}"
192.168.23.2
$ echo "${IPLO}"
127.0.0.1

这假定eth0lo接口的顺序,但是它显示了基本思想.

This assumes the order of the eth0 and lo interfaces, but it shows the basic idea.

这篇关于捕获bash命令的输出,将其解析并存储到不同的bash变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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