Redirect STDOUT/STDERR

Sometimes you want to redirect your shell script’s STDOUT/STDERR to a log file. This is pretty simple to do, ie:

./myscript.sh &> output.log

But sometimes you want to do the redirect inside the script itself ( ie, maybe redirecting is conditional, or maybe the file name is conditional on something only the script knows about)


#!/bin/bash

exec >> output.log
exec 2>&1

>&2 echo "This was printed to stderr"
echo "This was printed to stdout"

Or if you want to write to both a file and the terminal:

#!/bin/bash

exec 1> >(tee -a output.log)
exec 2>&1

>&2 echo "This was printed to stderr"
echo "This was printed to stdout"

Stackoverflow has other ways to do it:

Redirect STDOUT/STDERR

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s