Run the output of the bash command, parse it and save it in different bash variables

Explanation:

I have a small bash script that just runs any Linux command (e.g. ifconfig )

Typical ifconfig output looks something like this:

 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 all the output in a file / variable and analyze based on that. However, I want to know if there is anyway that I can put certain parts of the output in more than one variable (say, a bash variable called ${IPETH0} to transfer the IP address 10.106.145.12 with eth0 and ${IPLO} to transfer the IP address 127.0.0.1 from lo in the above example without executing the ifconfig command twice).

Something like what the tee command does with input, but I want to do this for output and save the output in 2 or more variables at a time. Any ideas?

+8
linux scripting bash shell
source share
3 answers
 $ read IPETH0 IPLO <<< $(ifconfig | awk '/inet[[:space:]]/ { print $2 }') $ echo "${IPETH0}" 192.168.23.2 $ echo "${IPLO}" 127.0.0.1 

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

+7
source share

You can use awk and bash arrays:

 arr=( $(awk -F ':' '$1 == "inet addr"{sub(/ .*/, "", $2); print $2}' < <(ifconfig)) ) 

Then you can do:

 read IPETH0 IPLO <<< ${arr[@]} 
+3
source share

you can read each ifconfig line and set the variables:

 while read l1 ;do if [[ $l1 =~ inet ]];then set -- $l1 echo "ip is $2 " fi done < <(ifconfig) 
+2
source share

All Articles