1

My understanding is that a pipe in shell like a | b redirects b's stdin to a's stdout. However, I tried ls | less < somefile, the behavior is very strange. less shows the output of ls concatenated by the content of somefile.

Could someone explain this phenomenon?

3

Your understanding is not quite correct. In a | b the stdout output of process a connected through a pipe to stdin of process b. The problem with your code is that with an additional redirection from somefile to process b you will use two different methods at the same time to connect to stdin of process b. Don't do that! The question is; what do you try to achieve (with such a construct) in the first place?

3

You don't say what shell are you using. From the behaviour you are describing it's likely zsh. If you have a look in its man page you would notice how redirections are handled.

Note that a pipe is an implicit redirection; thus

  cat bar | sort <foo

is equivalent to cat bar foo | sort (note the order of the inputs).

Otherwise, regular behaviour e.g., that one of bash is that each redirection replaces the previous redirection for that file descriptor.

zsh man page continues:

If the MULTIOS option is unset, each redirection replaces the previous redirection for that file descriptor. However, all files redirected to are actually opened, so

  echo foo > bar > baz

when MULTIOS is unset will truncate bar, and write `foo' into baz.

1

because you are taking input of less from somefile.

it works like this

1 -> execute ls , as you have used pipe , it will pipe stdout to stdin of next command : this is what you are telling

2 -> it will look second command.. it is less < somefile

as soon as it sees '<' redirection it will change stdin again to the file... Hence your previous change because of '|' is getting lost.

well, you can say it like this : less have taken input from file , it has nothing to do with ls's output.

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.