Fri, 26 Jul 2013

Redirect STDOUT and STDERR in Unix

One of the less well understood aspects of Unix are the default file descriptors. The default file descriptors for stdin, stdout, and stderr are 0, 1, and 2. These can be useful when you want to log error messages as well as the terminal output to a file, or to direct error messages to a different file from the standard output of a command.

For example, I needed to see if certain files were up on a website, so I wrote a shell script that used curl to check if the files were there, using curl's "-I" flag (which says, just perform a HTTP HEAD request against the URL). The problem is that curl, by default, shows a progress bar for each HTTP request, and that muddles up the output.

You can take stderr and pipe it to /dev/null and simultaneously take /dev/stdout and pipe it through the unix command head -1 (which gives me the HTTP HEAD status line like "HTTP/1.0 200 OK") to see if any of the files are not accessible.

Here's what that looks like:

curl -I http://site.example.com/somefile -# 2> /dev/null 1> /dev/stdout | head -1




Khan Klatt

Khan Klatt's photo