Shayan Toqraee
Shayan Toqraee

Reputation: 867

Shell IO redirection order, pipe version

I have seen this question: Shell redirection i/o order.

But I have another question. If this line fails to redirect stderr to file:

ls -xy 2>&1 1>file

Then why this line can redirect stderr to grep?

ls -xy 2>&1 | grep ls

I want to know how it is actually being run underneath.

It is said that 2>&1 redirects stderr to a copy of stdout. What does "a copy of stdout" mean? What is actually being copied?

The terminal registers itself (through the OS) for sending and receiving through the standard streams of the processes it creates, right? Does the other redirections go through the OS as well (I don't think so, as the terminal can handle this itself)?

Upvotes: 1

Views: 185

Answers (2)

Dario
Dario

Reputation: 2713

That answers my first question. What about the others?

Well, your second question has already been answered in the comments. (What is being duplicated is a file descriptor).

As to your last question(s),

The terminal registers itself (through the OS) for sending and receiving through the standard streams of the processes it creates, right? Does the other redirections go through the OS as well (I don't think so, as the terminal can handle this itself)?

it is the shell which attaches the standard streams of the processes it creates (pipes first, then <>’s, as you have just learned). In the default case, it attaches them to its own streams, which might be attached to a tty, with which you can interact in a number of ways, usually a terminal emulation window, or a serial console, whatever. Terminal is a very ambiguous word.

Upvotes: 2

P.P
P.P

Reputation: 121387

The pipe redirection (connecting standard output of one command to the stdin of the next) happens before the redirection performed by the command. That means by the time 2>&1 happens, the stdout of ls is already setup to connect to stdin of grep.

See the man page of bash:

Pipelines

The standard output of command is connected via a pipe to thestandard input of command2. This connection is performed before anyredirections specified by the command (see REDIRECTION below). If |&is used, command's standard error, in addition to its standardoutput, is connected to command2's standard input through the pipe;it is shorthand for 2>&1 |. This implicit redirection of thestandard error to the standard output is performed after anyredirections specified by the command.

(emphasis mine).

Whereas in the former case (ls -xy 2>&1 1>file), nothing like that happens i.e. when 2>&1 is performed the stdout of ls is still connected to the terminal (and hasn't yet been redirected to the file).

Upvotes: 4

Related Questions