BASH: while read line <<< $variable

How can you read from variable with ‘while read line’? This can save you disk writes.
You can write:

while IFS= read -r line
do
    echo "$line"
done <<< "$the_list"

IFS= sets $IFS to the empty string (so it doesn't contain any characters at all). In this case, since there's only one field, its only effect is to prevent the removal of leading IFS-characters from the start of the line.

or

If you do not use the variable for anything else, you can even do without it:

while read line ; do
    echo $line
done <<( ... code ... )

or

You can just use

your_code | while read line;
do
    echo $line
done

if you don't mind the while loop executing in a subshell (any variables you modify won't be visible in the parent after the done).

Scroll to top