Eugene Yarmash
Eugene Yarmash

Reputation: 149796

Why does "read" behave differently with the same input?

Why does read behave differently with the same input from a pipe and a heredoc:

printf "" | while read line; do echo "line=$line"; done   # outputs nothing    
while read line; do echo "line=$line"; done <<< ""        # outputs 'line='

How can I disable output in the second case?

Upvotes: 1

Views: 188

Answers (3)

kurt
kurt

Reputation: 26

How about using $'\c':

man bash | less -p '\\c * suppress trailing newline'

str=""
while read line; do echo "line=$line"; done <<<$'\c'"${str}"

str="abc"
while read line; do echo "line=$line"; done <<<$'\c'"${str}"

Upvotes: 1

geekosaur
geekosaur

Reputation: 61369

The here document has an implicit newline (\n) at the end; printf "" outputs nothing whatsoever. I don't know offhand of a way to get rid of the implicit newline.

Upvotes: 3

ewan.chalmers
ewan.chalmers

Reputation: 16235

If you can discard all empty lines...

while read line; do if test -n "$line"; then echo "line=$line"; fi; done <<< ""

Upvotes: 2

Related Questions