
When bash runs a command it forks a child process (see man 2 fork) that inherits all the file descriptors from the parent process, then it sets up the redirections that you specified, and execs the command (see man 3 exec).
In general you can write command n>file, which will redirect the file descriptor n to file.
Bash opens file for writing, gets the file descriptor for this file, and it replaces file descriptor 2 with the file descriptor of this file. So now anything written to stderr gets written to file.
As you can see both stdout and stderr now point to file. So anything written to stdout and stderr gets written to file.
Now bash processes the first redirection >file. We've seen this before and it makes stdout point to file:
Next bash sees the second redirection 2>&1. We haven't seen this redirection before. This one duplicates file descriptor 2 to be a copy of file descriptor 1 and we get:
Both streams have been redirected to file.
Now bash processes redirections left to right. It first sees 2>&1 so it duplicates stderr to stdout. The file descriptor table becomes:
Now bash sees the second redirect >file and it redirects stdout to file:
Do you see what happens here? Stdout now points to file but the stderr still points to the terminal! Everything that gets written to stderr still gets printed out to the screen! So be very, very careful with the order of redirects!
Similarly, by combining the previous one-liners, we can discard both stdout and stderr by doing:
5. Redirect the contents of a file to the stdin of a command
Here is an example. Suppose you want to read the first line of the file in a variable. You can simply do this:
Now you can read from the file descriptor 3, like this:
As you can see file descriptors don't have to be used in order, you can open any file descriptor number you like from 0 to 255.
17. Send stdout of one process to stdin of another process
As you can see, everything sent to file descriptor 1 (stdout) of command1 gets redirected through a pipe to file descriptor 0 (stdin) of command2.
First command1's stderr is redirected to stdout, and then a pipe is setup between command1's stdout and command2's stdin.
Next bash setups 3>&1 redirection. This creates file descriptor 3 to be a copy of file descriptor 1:
Next bash setups 1>&2 redirection. This makes file descriptor 1 to be a copy of file descriptor 2:
Next bash setups 2>&3 redirection. This makes file descriptor 2 to be a copy of file descriptor 3:
If we want to be nice citizens we can also close file descriptor 3 as it's no longer needed:
As you can see, file descriptors 1 and 2 have been swapped.| 欢迎光临 杰表技术论坛 (http://bwtvl16d.jatools.com/) | Powered by Discuz! 6.1.0 |