Bash 有条件地重定向标准。基于冗长级别

Bash conditionally redirect std. out based on verbosity level

我正在尝试实现详细级别标志,以便仅当详细级别大于特定阈值时,在我的脚本中执行的命令输出才会显示到标准输出。

我能够正确解析调用参数以确定详细级别(例如 -v -> 详细级别 1,-vvv -> 详细级别 3)。
现在我不确定如何使用。我最简单的方法是:

if test "$VERBOSE" -gt 2; then
    cmd 1>/dev/null
else
    cmd
fi

这个解决方案虽然正确,但似乎在我的脚本中引入了很多样板代码,如果我必须对每个命令都重复该代码的话。有没有更好更简洁的实现方式?

Is there a better and more concise way of achieving the same?

是的。您可以将代码集中在 shell 函数中。这甚至允许针对相同的 cmd.

有选择地应用或不应用重定向
my_cmd () {
   if test "$VERBOSE" -gt 2; then
       cmd "$@" 1>/dev/null
   else
       cmd "$@"
   fi
}
my_cmd -x arg1 arg2
other_cmd
cmd -x foo    # Do not apply redirection this time.

PS:这适用于所有 Bourne-heritage shell,因此我冒昧地将您的问题从 bash 重新标记为 shell。

I'd like to only redirect certains commands' output

选择一个免费的文件描述符并根据需要将其重定向到您想要的位置。 不同的文件描述符可以与不同的日志级别相关联。

if test "$VERBOSE" -gt 2; then
    exec 3>&1
else
    exec 3>/dev/null
fi
certain_command >&3
not_certain_command

另一种具有功能的设计:

log() {
     if test "$VERBOSE" -gt ""; then
          shift
          "$@"
     else
          shift
          "$@" >/dev/null
     fi
}
log 3 certain_command_with_logs_at_verbose_greater_then_3
log 1 certain_command_with_logs_at_verbose_greater_then_1
non_certain_command