1

running following command on zsh

zsh$ echo Hello | read str ; echo "str is: "$str

str is: Hello

whereas in bash, it doesn't work

bash$ echo Hello | read str ; echo "str is: "$str
str is: 

This thread mentions read command runs in subshell so current session has no clue about it. I'm not able to find why it works in zsh.

mohitmun
  • 5,379
  • 3
  • 18
  • 16
  • 2
    Because in `zsh` it doesn't run in a subshell? `ksh93` will also not run `read` in a subshell. – Kusalananda May 11 '18 at 07:28
  • 2
    In `ksh` and `zsh`, all except the last command in a pipeline will run in a subshell – Inian May 11 '18 at 07:30
  • @mohitmun : The other comments tell you all you need to know for your particular case, but also note that even without the context of a subshell, the `read` commands in bash and zsh are not identical. After all, bash and zsh are pretty different in many ways. – user1934428 May 11 '18 at 09:09

1 Answers1

3

The read command has the same behaviour in both shells, but bash runs the read in a subshell whereas zsh does not.

Some shells don't need to use a subshell for the read in your example (in general, the last command in a pipeline).

To avoid having to switch to another shell interpreter, you may have the read read from something other than a pipe:

read str <<<'hello'
printf 'str is %s\n' "$str"

Or, if all you want is to output the string, output it in the same subshell:

echo 'hello' | { read str && printf 'str is %s\n' "$str"; }
Kusalananda
  • 14,885
  • 3
  • 41
  • 52