Search code examples
for-loopvariablesash

In ash how to set multiple line output to variables


Edit #3: My question has been closed and marked as duplicate which I am unable to follow. I posted here because I was asking for help :(

enter image description here

I'm familiar with doing this type of thing in batch but can't work out how to do it in ash (edit: ash not bash). I'm searching an openwrt configuration file /etc/config/wireless for wifi-iface settings.

So far I can get the required output:

root@OpenWrt:~# awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g
default_radio0
default_radio1
wifinet1

My question is how can I turn this output into variables like using a for f loop?

Edit #1: Something like:

root@OpenWrt:~# echo $a
default_radio0

root@OpenWrt:~# echo $b
default_radio1

root@OpenWrt:~# echo $c
wifinet1

Edit #2: I'm guessing i need to change the output from lines to string:

root@OpenWrt:~# awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g
 | xargs
default_radio0 default_radio1 wifinet1

Getting closer but then how does the for loop work?


Solution

  • You can capture the output of a command into a variable using the $(command) construct:

    wireless_list=$(awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g)
    for w in ${wireless_list} ; do
        # Do something with $w
        echo "$w"
    done
    

    Alternative approach, using array (which will be safer to evaluate):

    readarray -t wireless_list <<< "$(awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g)"
    for w in "${wireless_list[@]}" ; do
        # Do something with $w
        echo "$w"
    done