bashwhile-loopheredocherestring

While-loop over lines from variable in bash


Assume a file file with multiple lines.

$ cat file
foo
bar
baz

Assume further that I wish to loop through each line with a while-loop.

$ while IFS= read -r line; do
$   echo $line
$   # do stuff
$ done < file
foo
bar
baz

Finally, please assume that I wish to pass lines stored in a variable rather than lines stored in a file. How can I loop through lines that are saved as a variable without receiving the below error?

$ MY_VAR=$(cat file)
$ while IFS= read -r line; do
$   echo $line
$   # do stuff
$ done < $(echo "$MY_VAR")
bash: $(echo "$MY_VAR"): ambiguous redirect

Solution

  • You have several options:


    Note that the first two options will (in bash) create a temporary file on disk with the variable's contents, whereas the last one uses a FIFO.