Shell – How to Redirect Both stderr and stdout to /dev/null in /bin/sh

io-redirectionopenbsdshell

I have tried all sorts of ways to redirect both stdout and stderr to /dev/null without any success. I have almost my entire life run bash which I've never had this issue with, but for once in BSD I'm stuck with /bin/sh.

What I've tried:

if ls ./python* 2> /dev/null; then
    echo found Python
fi

… which works; if Python is not present it will mute the error messages from ls.
However, if python.tgz is present, a line with be outputted which looks like this:

# ./test.sh
./python-2.7.3p1.tgz

I've tried:

if ls ./python* &> /dev/null; then
    echo found Python
fi

and

if ls ./python* 2>1 > /dev/null; then
    echo found Python
fi

and

if ls ./python* > /dev/null; then
    echo found Python
fi

Nothing really works.
I can only redirect one of the outputs, not both at the same time.

Best Answer

This will work in any Posix-compatible shell:

ls good bad >/dev/null 2>&1

You have to redirect stdout first before duplicating it into stderr; if you duplicate it first, stderr will just point to what stdout originally pointed at.

Bash, zsh and some other shells also provide the shortcut

ls good bad &>/dev/null

which is convenient on the command-line but should be avoided in scripts which are intended to be portable.

Related Question