9

The following command outputs different results depending if it is run in bash or zsh:

ls -l > x | wc -l

If executed in a non-empty directory, bash always gives 0, while zsh gives the right number of files. x contains the output of ls -l, as expected.

Why doesn't it work in bash?

Bruno Parmentier
  • 1,219
  • 2
  • 14
  • 34
  • The only way zsh could make that work would be to play `tee` (reading the output from `ls -l` itself, and writing it twice, once to the file, and once to `wc -l`). That's... a rather intrusive and unusual feature for a shell to provide, as opposed to connecting `ls -l` *directly* to either the file `x` or the stdin of `wc -l`, and not having any hand in touching the content being processed. – Charles Duffy Apr 21 '15 at 21:57
  • One portable way to write this would be `ls -l | tee x | wc -l`. – Charles Duffy Apr 21 '15 at 22:03

2 Answers2

9

Read the MULTIOS documentation in the zshmisc man page. It's a feature of zsh which causes it to redirect the output to multiple files at the same time, and it can also be a pipe.

e.g.

ls >a >b

will get both a and b populated with the content of the directory.

from the zshmisc documentation:

If the user tries to open a file descriptor for writing more than once, the shell opens the file descriptor as a pipe to a process that copies its input to all the specified outputs, similar to tee, provided the MULTIOS option is set, as it is by default. Thus:

date >foo >bar

writes the date to two files, named foo and bar. Note that a pipe is an implicit redirection; thus

date >foo | cat

writes the date to the file foo, and also pipes it to cat.

To turn it on you do setopt multios, to turn off you do setopt nomultios:

$ setopt nomultios
$ ls -l > x | wc -l
0
$ setopt multios
$ ls -l > x | wc -l
36
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
4

The output from ls -l is redirected into a file called 'x'. There is no output to go into the pipe (it's all going into 'x'). This is the way most every standard shell works.

The question here isn't why bash doesn't work, the question is why does zsh do what it does.

Brad Lanam
  • 5,192
  • 2
  • 19
  • 29
  • If you have a new question, please ask it by clicking the [Ask Question](http://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. – bitoiu Apr 21 '15 at 22:23
  • 2
    @bitoiu This is an answer to this question, isn't it? I don't see a new question here. – Rup Apr 22 '15 at 00:40