Not sure if I used the right words in the title, I am trying to do this:

while read line; do
    echo "$line"
done;  <( echo "foo\n"; exit )

but it hangs, I don't think the while loop is getting any input from the echo process. Does anyone know the right way to do this and why this is wrong?

I could do this:

echo "foo" | while read line; do echo "$line"; done;

but I am looking to do it the first way just for learning purposes. I am not sure if I need process substitution or not.

  • 1
    Do you need the value in $line after the loop? Is the echo a placeholder for a generic command or for a fixed piece of static text? In any case, the ; after done prevents the loop from even seeing the result of the process substitution, and the exit is not needed (just as it's not needed at the end of any program). – Kusalananda May 9 '19 at 20:46

You definitely need Process Substitution if your script proceeds after the loop and wants to handle ${line}.

Take the semicolon away, and put an input redirection between the done and the Process Substitution:

done < <( echo "foo\n"; exit )

Note that you don't need an explicit exit to terminate execution of a Process Substitution.

However, for text files processing it is usually much better and much safer done using sed or awk, which also yield much better performance. If you really must use Bash to handle text lines, it is normally very recommended to rather do it like in: (showing only the first line of the loop)

while IFS= read -r line ; do

unless you really know that you need otherwise.

That is required for raw handling of input lines having blanks, newlines and backslashes, that otherwise Bash would parse, squeeze, and interpret as (respectively) separators and escape character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.