blog.up-link.ro
3May/100

Unix-like Tips and Tricks: BASH Redirection

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.

Example:

output example:

# sed 's/example.com/domain.com/g' 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 (0) Trackbacks (0)

No comments yet.


Leave a comment


*

No trackbacks yet.