Bash stream redirection

Bit of a complex one.

  • stdin is 0
  • stdout is 1
  • stderr is 2
  • there are generally 1021 other ad-hoc streams, 3–1023.

ps aux > out.txt takes stdout on lhs and writes to the file out.txt. > general syntax is e.g. 2>&1 which takes 2 (stderr) and connects it to what 1 is connected to. Note that bash looks ahead within a command and connects the streams according to pipes before applying stream redirects. Understand the following two examples, or check out the link at the bottom.

ps aux > filename 2>&1 redirects both stdout and stderr to file filename. Putting the 2>&1 before the > filename wouldcause 2 to be redirected to where 1 is pointing (the tty) and then redirect 1 to filename, causing same behaviour as ommitting 2>&1.

ps aux 3>&1 1>&2 2>&3 | grep init causes stderr to be grepped and stdout to go the tty (normally opposite things happen).

Explanation of stream redirection in bash

bash_stream_redirection.txt · Last modified: 2008/10/09 11:19 by jobriath
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki