SH conditional redirection

fljx asked:

I want to be able to redirect some output of my script to /dev/null based on a command line switch.
I don’t know how should I do it.

In a silly way, it would be something like this (in a too simplified way):

#!/bin/sh

REDIRECT=

if [ $# -ge 1 -a "$1" = "--verbose" ]; then
    echo    "Verbose mode."
    REDIRECT='1>&2 > /dev/null'
fi

echo "Things I want to see regardless of my verbose switch."

#... Other things...

# This command and others along the script should only be seen if I am in verbose mode.
ls -l $REDIRECT

Any clues, please?

Thanks people.

My answer:


I believe your test is backwards. You want to redirect to /dev/null when not in verbose mode:

if [ $# -ge 1 -a "$1" = "--verbose" ]; then
    echo    "Verbose mode."
else
    REDIRECT='2>&1 >/dev/null'
fi

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.