根据变量的状态重定向命令的输出

Redirect output for commands based on state of variable

我在 bash 脚本中有许多命令 >/dev/null 2>&1 用于将 stdout 和 stderr 重定向到 /dev/null。

假设我有一个名为 echoOn 的变量,它可以是 0 或 1。

如果 echoOn 等于 0,那么我希望保留脚本中命令的重定向。如果等于1,那么我不希望重定向到位,所以命令可以输出。

我不想抑制所有命令的输出,而只抑制脚本中特定命令的输出。

有没有更抽象的方法让我无需手动向每个有问题的命令添加 if 语句来执行此操作?

我愿意拥有一个函数,我可以在其中传递命令及其参数,并将每个命令替换为对上述函数的调用和要执行的命令。

我不确定我是否正确理解了您的要求,但是怎么样:

# put the lines below at the beginning of the script
if (( echoOn == 0 )); then
    exec 3>/dev/null 2>&3
else
    exec 3>&1
fi

# then execute your commands
echo foo >&3    # a command which wants to switch the redirection
echo warn >&2   # simulates an error
echo bar        # a command which does not need the switch

如果echoOn设置为0,终端只显示bar

问题是您需要修改代码,将所有 >/dev/null 2>&1 表达式替换为 >&3

[更新]

为了控制特定命令的 stdout 和 stderr,请尝试以下操作:

echoOn=0        # set to "1" to ebable stdout/stderr else set to "0"
if (( echoOn == 0 )); then
    exec 3>/dev/null
    exec 4>/dev/null
else
    exec 3>&1
    exec 4>&2
fi

echo foo 1>&3 2>&4          # a command which wants to switch the redirection
(echo warn >&2) 1>&3 2>&4   # simulates an error
echo bar                    # a command which does not need the switch
(echo error >&2)            # simulates anerror

请将1>&3 2>&4添加到您要控制其输出的命令中

试试这个:

if [ $# -ge 1 -a  -eq 0 ]; then
    exec 3>/dev/null 1>&3 2>&3
else
    exec 3>&1
fi

foo="hello"
warn="world"
bar="Whosebug"


# then execute your commands
echo $foo >&3    # a command which wants to switch the redirection
echo $warn >&2   # simulates an error
echo $bar        # a command which does not need the switch

I have many commands in a bash script that have >/dev/null 2>&1 used to redirect stdout and stderr to /dev/null.

不使用 $ 来获取变量的值。我认为如果您尝试 运行 脚本,您可能会出错。并且您需要同时重定向 stdout 和 stderr。因此,如果您将参数 0 传递给脚本,我的脚本将两者都重定向到 /dev/null,否则它不会重定向。

没有输出如果你 运行 ./example.sh 0

输出./example 1

hello
world
Whosebug