2011年12月3日 星期六

bash redirection advance explaination

Back again to the "2>&1". Now that we know what it means, we can also apply it in other ways, like this:
#將ps aux 標準輸出的結果定向到filename ,標準錯誤也定向到filename
[rechosen@localhost ~]$ ps aux > filename 2>&1
The stdout output of ps aux will be sent to the file filename, and the stderr output, too. Now, this might seem unlogical. If bash would interpret it from the left to the right (and it does), you might think that it should be like:
#ps aux 的標準輸出,和標準錯誤 兩個資訊結果先傳給terminal, 之後標準輸出傳至filename
但標準錯誤卻沒有傳至filename
[rechosen@localhost ~]$ ps aux 2>&1 > filename


Well, it shouldn't. If you'd execute the above syntax, the stderr output would just be echoed to the terminal. Why? Because bash does not redirect to a stream, but to the current final destination of the stream. Let me explain it:
  • First, we're telling bash to run the command "ps" with "aux" as an argument.
  • Then, we're telling to redirect stderr to stdout. At the moment, stdout is still going to the terminal, so the stderr output of "ps aux" is sent to the terminal.
  • After that, we're telling bash to redirect the stdout output to the file filename. The stdout output of "ps aux" is sent to this file indeed, but the stderr output isn't: it is not affected by stream 1.
If we put the redirections the other way around ("> filename" first), it does work. I'll explain that, too:
  • First, we're telling bash to run the command "ps" with "aux" as an argument (again).
  • Then, we're redirecting the stdout to the file filename. This causes the stdout output of "ps aux" to be written to that file.
  • After that, we're redirecting the stderr stream to the stdout stream. The stdout stream is still pointing to the file filename because of the former statement. Therefore, stderr output is also written to the file.
#將標準輸出傳到/dev/null  ,標準錯誤傳給grep init
[rechosen@localhost ~]$ ps aux 2>&1 > /dev/null | grep init
The syntax in this snippet will send the stderr output of "ps aux" to "grep init", while the stdout output is sent to /dev/null and therefore discarded. Note that "grep init" will probably not find anything in this case as "ps aux" is unlikely to report any errors.

沒有留言:

張貼留言