taT4Nix | Redirect STDERR to File or File Descriptor

$> cd /
$> find $PWD -type -f

If you change directory to root directory on any UNIX server and try the above find command, chances are you would see long list of error messages along with few search results.

Mostly, the error would be Permission denied, one would like to suppress such messages, as they are not helping in achieving the desired results. In that scenario, do the following;

$> cd /
$> find $PWD -type -f 2> /dev/null

There you go, looks simple isn’t it?

2> means redirect STDERR to the file or file descriptor on the right-hand side of output-redirection operator.

In our case, it would be a file known as /dev/null, however there could be scenarios when your command’s output is redirected to some file, yet the error messages are getting printed on the STDOUT (as it is by default).

To handle that, do the following;

$> cd /
$> find $PWD -type -f > $HOME/sample_logfile.log 2>&1

Using 2>&1 would redirect the STDERR to file descriptor for STDOUT, i.e. &1 However, STDOUT is already redirected to $HOME/sample_logfile.log So, effectively STDERR and STDOUT are both being redirected to same logfile.

That’s all for today, keep scripting 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s