How do I conditionally redirect the output of a command to /dev/null?

前端 未结 4 1592
不思量自难忘°
不思量自难忘° 2020-12-31 04:51

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         


        
4条回答
  •  暖寄归人
    2020-12-31 05:17

    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*
    
    SILENT=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)

提交回复
热议问题