3

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.

bahamat
  • 6,433
j4x
  • 105

3 Answers3

7

Tie STDOUT to another handle if you are in verbose mode, otherwise link those handles to /dev/null. Then write your script so the optional stuff points to the extra handles.

#!/bin/sh

exec 6>/dev/null

if [ $# -ge 1 -a "$1" = "--verbose" ]; then
echo    "Verbose mode."
exec 6>&1
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 >&6 2>&1

That should get you started. I'm not sure if that is BASH specific or not. It was just a memory of long ago. ;-)

AmanicA
  • 103
Mark
  • 2,258
4

I don't know about sh but in bash (not the same!) you'll need to use eval:

$ x='> foo'
$ echo Hi $x
Hi > foo
$ eval echo Hi $x
$ cat foo
Hi
DerfK
  • 19,826
0

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
Michael Hampton
  • 252,907