Redirect / Log the Output of a Bash Shell Script from within the Script

It is a common practice to use 1>/dev/null 2>&1 after commands to suppress any kind of output completely. The same technique is also used to redirect the output to a text file for logging purposes instead of /dev/null. For eg.

echo "hello" 1>/tmp/hellolog 2>&1

However if you are writing a rather long bash script, it is frustrating to add that at the end of every command whose output you want logged. It would be convenient to have one single setting, so that any output produced by the commands within the script is redirected to a log file. Well surprisingly, its extremely simple to setup your script for the above functionality. All you need is an extra line of code at the top of your bash file.

exec &>/tmp/log

If you have the above line in your script, all output (STDOUT and STDERR) will be redirected to /tmp/log. So the first eg. of the echo command can also be written as:

#!/bin/bash
exec &>/tmp/hellolog
echo "hello"

Infact the construct &>/tmp/log is equivalent to 1>/tmp/log 2>&1 and can be used interchangeably. &>/tmp/log would create a new /tmp/log everytime you execute the script. If you want the output to be appended, instead of overwriting the file, add this at the top of your script instead.

exec &>>/tmp/log

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.