A little help redirecting stderr to stdout

Written by:

When writing shell scripts, there are times when I want to have the output captured and redirected into a file. Noticing that error messages from the script such as possible syntax errors are not written to the output file. This is because stderr and stdout are 2 separate file handles. Think of it as you trying to open two different files.

Stderr’s file descriptor is the number 2 and stdout’s file descriptor is the number 1.

So in it’s simplest term, to redirect stderr to stdout you would want

2>&1

Notice the & sign. Without this you are basically saying redirect into a file called 1 vs a file handle of 1.

So let’s say we run the command

ls -alGobblyGook 2>&1

This would redirect any errors from this command into stdout.

s: invalid option -- 'y'
Try `ls --help' for more information.

Now lets say you want to redirect stderr to stdout but capture all the output into a file call /tmp/myoutput.out

ls -alGobblyGook > /tmp/myoutput.out 2>&1

There you have it. It will now redirect all the output to /tmp/myoutput.out and not display anything to the screen.

Some times you may want to run a command within a script just to get the return code but do not want the output or errors to show up.

Then this little tip is what you want:

rc="`ps -ef | grep -v grep | grep smon > /dev/null 2>&1`"
echo $rc

What this does is do a ps to list all processes looking for the process name or text of “smon” but not anything with the word grep which would be the command that we are currently running.

Let’s say you have a script that performs a number commands and you want to capture stderr and stdout for the entire script without doing the described above > /tmp/myoutput.out 2>&1 stuff.

At the top of your script, do something like this:

#!/bin/sh
exec 2>&1
exec 1>/tmp/myoutput.out

some commands
more commands
etc...
A little help redirecting stderr to stdout
0 votes, 0.00 avg. rating (0% score)

Leave a Reply