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"



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.