Rajshekar Iyer
Rajshekar Iyer

Reputation: 111

Bash: Read lines from variable . Nested loop

I am able to read line by line in the first loop, but 2nd loop returns all lines at once.
I want the second loop to read line-by-line similsr to the outer loop. How can I resolve this?

firstlist=`<some command that returns multi-line o/p>`
if [ "x$firstlist" != "x" ] ; then
    printf %s "$firstlist" |while IFS= read -r i
    do
        secondlist=`<some command that returns multi-line o/p>`
        if [ "x$secondlist" != "x" ] ; then
            printf %s "$secondlist" |while IFS= read -r j
            do
                doverify $i $j
            done
        else
            echo "Some message"
        fi
     done
else
    echo "some other message"
fi

Upvotes: 0

Views: 2604

Answers (2)

Rajshekar Iyer
Rajshekar Iyer

Reputation: 111

This worked for me as follows

firstlist=`<some command that returns multi-line o/p>`
  if [ "x$firstlist" != "x" ] ; then
  while IFS= read -r i
  do
    secondlist=`<some command that returns multi-line o/p>`
    if [ "x$secondlist" != "x" ] ; then
        while IFS= read -r j
        do
            doverify $i $j
        done <<< "$secondlist"
    else
        echo "Some message"
    fi
   done <<< "$firstlist"
else
  echo "some other message"
fi

Reference: http://mywiki.wooledge.org/BashFAQ/001 The <<< construct is called "here string" per the link

Upvotes: 0

Vlad
Vlad

Reputation: 35594

You should use -a instead of -r.

Example:

{0,244}$> echo "a b c" | { read -a j; echo ${j[0]}; echo ${j[1]}; echo ${j[2]}; }
a
b
c

Upvotes: 1

Related Questions