Redirecting and pipe behavior in bash vs. zsh

The following command prints different results depending on whether it runs in bash or zsh:

ls -l > x | wc -l 

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

Why doesn't it work in bash?

+6
source share
2 answers

Read the MULTIOS documentation on the zshmisc manual zshmisc . This is a zsh function that forces it to redirect output to multiple files at the same time, and can also be a channel.

eg.

 ls >a >b 

will receive both a and b filled with the contents of the directory.

from the zshmisc documentation:

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

 date >foo >bar 

writes the date to two files named foo and bar . Note that the channel is an implicit redirect; In this way,

 date >foo | cat 

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

To enable it, do setopt multios to disable the setopt nomultios function:

 $ setopt nomultios $ ls -l > x | wc -l 0 $ setopt multios $ ls -l > x | wc -l 36 
+8
source

The output from ls -l redirected to a file named 'x'. There is no way out into the pipe (all this happens in "x"). This is how most standard shells work.

The question here is not why bash does not work, the question is why zsh does what it does.

+2
source

Source: https://habr.com/ru/post/985639/


All Articles