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


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

both just print foo once.


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

To disable it, just set nomultios option:

$ setopt nomultios
  • Ah, I didn't know zsh could do that! I (basically) understand redirection, I wanted to know why the command wasn't equivalent to {echo foo >&2} | grep foo, if you see what I'm trying to say. I thought the command I asked about above would have redirected stdout to stderr and then piped empty stdout to grep. – Zorawar Jun 29 '15 at 18:45
  • @Zorawar: That question was not addressed in your post, so I will answer here. In {echo foo >&2} | grep foo, {echo foo >&2} was considered as a command, and it ran in a subshell. You can think it like A | grep foo where A is {echo foo >&2}. In this case, >&2 and | were separated, MULTIOS has no effect here. – cuonglm Jun 29 '15 at 18:58
  • @Zorawar This case is why I ended up turning off multios. It's a cute idea, but in practice I found it often annoying and rarely useful. – Gilles 'SO- stop being evil' Jun 29 '15 at 22:45
  • @cuonglm, I have another question that is asked here but didn't get any answer. If you know it and also have time, could you please help? – Liu Sha Jan 11 '19 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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