Reading a variable line by line with while loop
PleegWat
pleegwat at telfort.nl
Tue Dec 1 22:01:47 UTC 2009
Alan McKay wrote:
>> echo "$Variable" | while read
>> ...
>> done
>>
>> has better chances of working.
>
> This method has gotchas though, and I try to avoid it. The pipe
> causes the while to execute in a sub shell and so any variable changes
> you make inside the loop will be lost when you get out of the loop.
> For this reason I often actually create a file and do the redirect as
> per the original post
>
> e.g.
>
> while stuff
> do
> done < file
Another (bash-specific) solution:
while condition
do stuff
done < <(command)
The <(command) construct runs `command`, redirects stdout to a pipe, and
returns the name of the named pipe.
This construct has the disadvantages of being bash-specific and
resulting in hard-to-read code.
Two more solutions specifically for input from a variable: Heredoc
while condition
do stuff
done <<EOF
$variable
EOF
Or herestring (bash-specific)
while condition
do stuff
done <<< "$variable"
PleegWat
More information about the ubuntu-users
mailing list