Using kernel 2.6.x

This is to complete a solution from a previous question - How to iterate through a variable while skipping one of the values?.

How can you extract a value, by position, from two variables and concatenate them into a third value with the same positions ?

On this OS, non-sh shells are installed as Entware-NG packages and can't be used since they load after the script runs. As a result, the solution needs to be based on a Posix sh as it is the only shell available when the script runs.

For example, use the following variables ...

NETID="10 20 30"
NAME="eth1 eth2 eth3"

... and create a third variable with the following values.

NETS="eth1:10 eth2:20 eth3:30"
  • 3
    As NETID and NAME are probably constructed from the same source (e.g. ifconfig), my proposal in the other question was that you show us how NETID and NAME are built and that you ask us to adapt the code to build NETS instead. That would probably be less cumbersome. BTW, it's worth mentioning that you want answer based on (POSIX) sh. – xhienne Sep 12 '17 at 23:32
  • 1
    wouldn't Wildcard's awk solution work similarly here? – Jeff Schaller Sep 13 '17 at 0:17
  • @xhienne - Currently, the values in $NETID and $NAME are manually input since different hosts may have values that are already in use or not available. – uihdff Sep 13 '17 at 17:15

You may prefer a sh-only answer. Here is one that works with a POSIX shell:

NETS=$(set -- $NETID; for iface in $NAME; do echo "$iface:$1"; shift; done)

Commented version:

    set -- $NETID            # Sets the shell parameters to the content of NETID
    for iface in $NAME; do   # For each interface name...
        echo "$iface:$1"
        shift                # First shell parameter is now the next NETID, if any

Please note that, due to the $(...) construct, everything occurs in a sub-shell and that the parameters of the parent shell are not affected.

  • That's an amazingly simple and clear answer. Thank you ! – uihdff Sep 13 '17 at 22:19
  • Why not use set -- $NETID? Was that a deliberate decision for some reason? – Wildcard Sep 19 '17 at 21:36
  • 1
    @Wildcard You mean why not use --, right? Because NETID is known and cannot begin with a - or a +. Not really deliberate, I'll add it, it won't hurt. – xhienne Sep 19 '17 at 21:41
NETID="10 20 30"
NAME="eth1 eth2 eth3"

NETS=$(awk -v name="$NAME" -v netid="$NETID" '
    size=split(name, arr_names); 
    split(netid, arr_netids);
    for(i=1; i <= size; i++) {
        printf "%s:%s ", arr_names[i], arr_netids[i];

echo "$NETS"


eth1:10 eth2:20 eth3:30 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.