如何有条件地将命令输出重定向到/dev/null? [英] How do I conditionally redirect the output of a command to /dev/null?

查看:118
本文介绍了如何有条件地将命令输出重定向到/dev/null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个剧本.我想给这个脚本一个安静的模式和一个冗长的模式.

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

这等效于:

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

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

与为每个受影响的语句编写if-elses相比,我真的希望有一种更好的方法.

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

eval可以工作,但是对其他变量有明显的副作用.

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

推荐答案

您可以编写包装函数:

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)

这篇关于如何有条件地将命令输出重定向到/dev/null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆