BASH Shell Redirect Output and Errors To /dev/null

How do I redirect output and errors to /dev/null under bash / sh shell scripting? How do I redirect the output of stderr to stdout, and then redirect this combined output to /dev/null device? In Unix, how do I redirect error messages to /dev/null?

You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2). [donotprint][/donotprint]So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.

Syntax to redirect error and output messages to /dev/null

The syntax discussed below works with Bourne-like shells, such as sh, ksh, and bash:

$ command > /dev/null 2>&1
$ ./script.sh > /dev/null 2>&1
$ ./example.pl > /dev/null 2>&1

$ command > /dev/null 2>&1
$ ./script.sh > /dev/null 2>&1
$ ./example.pl > /dev/null 2>&1

OR

command &>/dev/null
job arg1 arg2 &>/dev/null
/path/to/script arg1 &>/dev/null

command &>/dev/null
job arg1 arg2 &>/dev/null
/path/to/script arg1 &>/dev/null

You can also use the same syntax for all your cronjobs to avoid emails and output / error messages:
@hourly /scripts/backup/nas.backup >/dev/null 2>&1
OR
@hourly /scripts/backup/nas.backup &>/dev/null

Redirect both standard error and standard out messages to a log file

You can always redirect both standard error (stdin) and standard out (stdout) text to an output file or a log file by typing the following command:

command > file 2>&1
/path/to/my/cool/appname > myapp.log 2>&1

command > file 2>&1
/path/to/my/cool/appname > myapp.log 2>&1

Want to close stdout and stderr for the command being executed on a Linux/Unix/BSD/OSX bash shell?

Try the following syntax:

## Thanks http://sxi.io/how-to-redirect-output-and-errors-to-devnull/#comment-40252 ##
command 1>&- 2>&-
 
## Note: additional '&' at the end of job to put it in backgrounds ##
job 1>&- 2>&-  &
command 1>&- 2>&-  &

## Thanks http://sxi.io/how-to-redirect-output-and-errors-to-devnull/#comment-40252 ##
command 1>&- 2>&- ## Note: additional ‘&’ at the end of job to put it in backgrounds ##
job 1>&- 2>&- &
command 1>&- 2>&- &

See man pages: ksh(1)

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.