Bruno Parmentier
Bruno Parmentier

Reputation: 1239

Redirection and pipe behavior in bash vs. zsh

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?

Upvotes: 9

Views: 2571

Answers (2)

Anya Shenanigans
Anya Shenanigans

Reputation: 94614

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

Upvotes: 9

Brad Lanam
Brad Lanam

Reputation: 5723

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.

Upvotes: 4

Related Questions