How to use for/while loop with multiple variables?

Hi,

I have two variables like below which will always be of the same size
a=1:2:3
b=A:B:C

I need to use a for/while loop that will have both the variables available. I cannot use an array here and will probably might iterate through the variable as echo $a | tr ':' '\n' and thus iterate through the variables one by one. I am doing the below

 
for i in `echo $a | tr ':' '\n'`
do
  echo "the variable is $i"
done

But I want to traverse both the lists at the same time. So for eg if I have the first element in list 1, I should also have the first element in list 2. I could have done this with a count variable, but wanted to see if there is another easy way

You don't need backticks and tr, the shell's own built-in splitting will suffice.

How about this?

OLDIFS="$IFS"
IFS=":"

set -- $a # Sets $1 $2 ...  parameters to 1 2 ...

for x in $b
do
        echo $x $1
        shift # Removes first parameter, so 1 2 ... becomes 2 ...
done

IFS="$OLDIFS"
2 Likes

Thanks a bunch for the quick response. Is there a way you can help me with this using the same format , like the "echo" and "trim". The codereview people will ask for consistency and all our coding has been done previously in this fomat. So I was trying to get something in the same format

If the code review people expect your code to remain overblown and bugprone because all your code before was too, both you and your reviewers have a big problem...

You have everything you need to do this yourself if you insist on doing so. Remove all the IFS stuff, and anywhere you see a simple easy $a and $b, slap in one of your big echo | tr kludges.

In case it's an oversight, be aware that command substitution strips all trailing newlines. If there are empty fields at the end of $a, they will be lost.

Regards,
Alister

All bash:

while IFS=: read i && IFS=: read j<&3
do
  printf "%s\n" "$i, $j"
done <<<"${a//:/$'\n'}" 3<<<"${b//:/$'\n'}"