How to run a script and have it output nice logs for you in bash

It is standard when you are writing your script, to write errors to “Standard Error” ( STDERR ). Like so:

echo "Unique ID and Error" >&2

Usually when you run a script it outputs both standard error and standard output to your terminal display. You can however redirect those to log files.

If you want just the standard output to be logged (errors will still be displayed in your terminal):

./myscript > scriptlog.txt

If you want your errors to be logged to a file and have the standard output still displayed in your terminal:

./myscript 2> errorlog.txt

For having them outputted to different files:

./myscript > scriptlog.txt 2> errorlog.txt

Finally, if you want both standard error and standard output to be sent to the same file:

./myscript > scriptlog.txt 2>&1

Also, you can use this same redirection to make the script completely silent (For instance when you are running the script as a cronjob, and do not want it to send you email):

./myscript > /dev/null 2>&1

Leave a Reply

Your email address will not be published. Required fields are marked *

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