Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress stdout and stderr in bash

Tags:

bash

I was trying to make a little script when I realized that the output redirection &> doesn't work inside a script. If I write in the terminal

dpkg -s firefox &> /dev/null

or

dpkg -s firefox 2>&1 /dev/null

I get no output, but if I insert it in a script it will display the output. The strange thing is that if I write inside the script

dpkg -s firefox 1> /dev/null

or

dpkg -s firefox 2> /dev/null

the output of the command is suppressed. How can I suppress both stderr and stdout?

like image 655
sinecode Avatar asked Nov 29 '22 22:11

sinecode


1 Answers

&> is a bash extension: &>filename is equivalent to the POSIX standard >filename 2>&1.

Make sure the script begins with #!/bin/bash, so it's able to use bash extensions. #!/bin/sh runs a different shell (or it may be a link to bash, but when it sees that it's run with this name it switches to a more POSIX-compatible mode).

You almost got it right with 2>&1 >/dev/null, but the order is important. Redirections are executed from left to right, so your version copies the old stdout to stderr, then redirects stdout to /dev/null. The correct, portable way to redirect both stderr and stdout to /dev/null is:

>/dev/null 2>&1
like image 77
Barmar Avatar answered Dec 04 '22 05:12

Barmar