sinecode
sinecode

Reputation: 804

How to suppress stdout and stderr in 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?

Upvotes: 9

Views: 16044

Answers (3)

Joviano Dias
Joviano Dias

Reputation: 1110

Additional guidance to stderr (error) and stdout (output) suppression

Suppress output only

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

Suppress error only

dpkg -s firefox 2> /dev/null

Suppress output and error

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

# You can read this as 2 (stderr) goes wherever 1 (stdoutput) goes. i.e. /dev/null. 

/dev/null is the the blackhole in unix, where if anything that is sent is gone forever.

Upvotes: 3

Barmar
Barmar

Reputation: 780724

&> 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

Upvotes: 27

pedromss
pedromss

Reputation: 2453

Make file descriptor 2 (stderr) write to where File descriptor 1 (stdout) is writing

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

This will suppress both sources.

Upvotes: 10

Related Questions