简体   繁体   中英

Why read builtin command has different behaviour on zsh and bash?

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.

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"; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM