zsh I/O redirection: redirecting and then piping; what is going on?

Can somebody explain what is going on in this command:

echo foo >&2 | grep foo

Zsh (5.0.2) prints foo twice. One seemingly to stdout and one to stderr, since running these commands:

{ echo foo >&2 | grep foo } >/dev/null

and:

{ echo foo >&2 | grep foo } 2>/dev/null

both just print foo once.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

That’s the effect of MULTIOS.

echo foo >&2 | grep foo

will write foo to stderr and also pipe foo to grep. Because stderr defaults to terminal, you will see two foo lines, one from echo, one from the grep result.

{ echo foo >&2 | grep foo } >/dev/null

Here, you saw one line because stdout was redirected to /dev/null, you only saw the foo line from echo.

{ echo foo >&2 | grep foo } 2>/dev/null

Here, you saw one line because stderr was redirected to /dev/null, you only saw the foo line from grep.

You can easily see the difference in the terminal by the line output color. grep will highlight the matched pattern (or you can force it to by using --color=always).


MULTIOS was enabled by default with nomultios option unset:

$ unsetopt | grep nomultios
nomultios

To disable it, just set nomultios option:

$ setopt nomultios


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x