tags:

views:

87

answers:

3

I have a script. I would like to give this script a quiet mode and a verbose mode.

This is the equivalent of:

if $verbose
then
  redirect="> /dev/null"
fi

echo "Verbose mode enabled" $redirect # This doesn't work because the redirect isn't evaluated.

I'd really like a better way of doing this than writing if-elses for every statement affected.

eval could work, but has obvious side effects on other variables.

A: 

Not perfect, but how about setting redirect to either "/dev/null" or "/dev/tty", and then doing

{
   echo "verbose"
    ....
} > $redirect
Paul Tomblin
`/dev/stdout`, not `/dev/tty`. Using the latter will always cause it to go to the display even if the script is redirected.
Ignacio Vazquez-Abrams
+5  A: 

Got the idea from another question:

#!/bin/sh

if [ $SILENT ]; then
    exec &>/dev/null
fi

echo "Silence here."
jholster
That test for your if will give errors if SILENT is the empty string.
Jefromi
`if [ -n "$SILENT" ]`
Dennis Williamson
+3  A: 

You could write a wrapper function:

redirect_cmd() {
    # write your test however you want; this just tests if SILENT is non-empty
    if [ -n "$SILENT" ]; then
        "$@" > /dev/null
    else
        "$@"
    fi
}

You can then use it to run any command with the redirect:

redirect_cmd echo "unsilenced echo"
redirect_cmd ls -d foo*

SILENCE=1
redirect_cmd echo "nothing will be printed"
redirect_cmd touch but_the_command_is_still_run

(If all you need to do is echo with this, you can of course make the function simpler, just echoing the first argument instead of running them all as a command)

Jefromi
I like this solution. `echo` was just an example. I could have picked a better one.
Lawrence Johnston
The example is incorrect; use `"$@"`, not `$@`.
vladr
@Vlad: Oops. I don't know what happened to my usual obsessive quoting there. Edited!
Jefromi