Bash: Suppressing script output

Recently I have been creating a bunch of bash scripts to automate some processes, I normally run these scripts manually so output is helpful but today I was working on a script which runs via a cronjob every 12 hours, the issue with this is that if a script outputs any data whilst being executed via cron the output is emailed to the user which ran it. This was causing an email to be sent to my inbox every 12 hours which I didn’t want (yes it allows me to verify it has run but I didn’t need to know this or want an email every 12 hours).

The answer is simple all I had to do was redirect the stdout output to a file or null location. This is achieved using the following command.

scriptname >/dev/null

What this does is send any output which was going to stdout to /dev/null so we no longer see the output. This however doesn’t hide error messages (stderror) either of the following two commands will redirect error messages.

scriptname >/dev/null 2>&1
scriptname >/dev/null 2>/dev/null

You can replace /dev/null with an actual file such as /home/shane/run_log.log and now output will be redirected to that file, the first line above directs both messages (stdout) and error messages (stderror) to the same location /dev/null, the second command however can be used to direct messages and error messages to separate locations / files.

scriptname >/dev/null 2>/home/shane/run_error.log

The following line will suppress normal message output but error output will be stored into run_error.log. Because we are writing to a file and not the shell output we no longer receive the output in an email.

Leave a Reply

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