Why -while read line- does not work with stdout

Written by - 0 comments

Published on - Listed in Linux Shell Coding

For some reason I was stuck in further developing of check_equallogic because of one little bugger: I couldn't get shell outputs (several lines) into one array. This has been frustrating since it didn't make any sense to me, why Bash wouldn't correctly read the lines into an array. Until I understood. My mistake:

i=1 cat /etc/resolv.conf | while read line; do myarray[$i]=$line; (( $i+1 )); done

It might seem correct - but it isn't. Thanks to this forum topic I finally understood that 'while' opens its own shell and is not able to read the values: The while statement is part of a pipeline and runs in its own shell so the array value is not available to the main script.. So the solution is done with a for loop (why didn't I think of that before, ouch!):

i=0 for line in $(cat /etc/resolv.conf); do myarray[${i}]=$line; i=$(($i + 1 ));done

And that's actually why I love working in the IT sector: You never finish to learn (= it never get's boring)!

Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.