1

This question already has an answer here:

bash builtin command read is said to accept input from stdin, but why does the following not read in anything?

$ printf "%s" "a   b" | read line
$ printf "%s" "$line"
$

Thanks.

marked as duplicate by Jeff Schaller, DopeGhoti, Stephen Harris, peterh, Wieland Jan 1 at 17:15

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

The problem is not with read itself, but with the pipe. In bash, that causes the second command (read, in this case) to run in a subshell. So it will actually read into a line variable, only that variable exists in a subshell and will vanish as soon as the pipeline completes.

(Note that other shells behave differently, most notably ksh will run the last command of a pipeline in the current shell, so this snippet might work in ksh. In bash it will not work, as you're seeing.)

A possible solution is to use <(...) process substitution for the first part of the pipeline, with an additional < to redirect that to stdin:

read line < <(printf "%s" "a   b")

In this particular case, you could do without the printf command, then <<< would also work:

read line <<<"a   b"

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