android bsd linux unix & open-source world


Unix-like Tips and Tricks: BASH Redirection

WP Greet Box icon
Hello there! If you are new here, you might want to subscribe to the RSS feed or subscribe via E-mail for updates on this topic.

Bash is a POSIX shell with a number of extensions. It is the shell for the GNU operating system from the GNU Project. It can be run on most Unix-like operating systems.

In this article I'll talk about bash redirections.

Unix has three standard file descriptors: stdin (input), stdout (output) and stderr (error output). By default, all of these descriptors are directed to the terminal, so all input comes from the terminal, and all output will go to the terminal.


output example:

# sed 's/' file.txt > output.txt

input example:

# while read line;do echo $line;done < input.txt

Often, you want to redirect both stdout and stderr to the same file:

# /etc/init.d/httpd 1>&2

does redirect stdout to stderr (and replacing 1>&2 with 2>&1 redirects stderr to stdout). However, if you want the output to go to a file, you have to do that before the redirection:

# /etc/init.d/httpd >output.txt 2>&1

NOTE: As far as the stdio library is concerned, stderr is unbuffered, while stdout is line-buffered when pointing to a terminal; so output may happen in the 'wrong' order when you mix them. However, this won't affect the way that programs like less deal with the output.

Print This Post Print This Post
Comments (1) Trackbacks (0)
  1. To make the output appear in the good order, use ‘stdbuf’ to unbuffer stdout.

    # stdbuf -o0 /etc/init.d/httpd >output.txt 2>&1

Leave a comment


No trackbacks yet.