[英]Capture output of a bash command, parse it and store into different bash variables
Explanation: 说明:
I have a small bash script which simply runs any Linux command (eg say ifconfig
) 我有一个小的bash脚本,它只运行任何 Linux命令(例如说
ifconfig
)
The typical output of ifconfig is something like this: 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)
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 ). 然而,我想知道是否有可能将输出的特定部分放在多个变量中(比如一个名为
${IPETH0}
的bash变量来从eth0携带IP地址10.106.145.12
并且${IPLO}
携带在上面的示例中,来自lo的IP地址127.0.0.1
没有运行ifconfig命令两次 )。
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. 类似于tee命令对输入执行的操作,但我想为输出执行此操作并将输出一次性存储到2个或更多变量中。 Any ideas?
有任何想法吗?
$ read IPETH0 IPLO <<< $(ifconfig | awk '/inet[[:space:]]/ { print $2 }')
$ echo "${IPETH0}"
192.168.23.2
$ echo "${IPLO}"
127.0.0.1
This assumes the order of the eth0
and lo
interfaces, but it shows the basic idea. 这假定了
eth0
和lo
接口的顺序,但它显示了基本思想。
You can use awk and bash arrays: 您可以使用awk和bash数组:
arr=( $(awk -F ':' '$1 == "inet addr"{sub(/ .*/, "", $2); print $2}' < <(ifconfig)) )
Then you can do: 然后你可以这样做:
read IPETH0 IPLO <<< ${arr[@]}
you can read each line of ifconfig and set variables : 你可以读取ifconfig的每一行并设置变量:
while read l1 ;do
if [[ $l1 =~ inet ]];then
set -- $l1
echo "ip is $2 "
fi
done < <(ifconfig)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.