SH 条件重定向

j4x*_*j4x 3 bash redirection sh

我希望能够/dev/null根据命令行开关将脚本的某些输出重定向到。我不知道我该怎么做。

以一种愚蠢的方式,它会是这样的(以一种过于简化的方式):

#!/bin/sh

REDIRECT=

if [ $# -ge 1 -a "$1" = "--verbose" ]; then
    echo    "Verbose mode."
    REDIRECT='1>&2 > /dev/null'
fi

echo "Things I want to see regardless of my verbose switch."

#... Other things...

# This command and others along the script should only be seen if I am in verbose mode.
ls -l $REDIRECT
Run Code Online (Sandbox Code Playgroud)

请问有什么线索吗?

谢谢人们。

Mar*_*ark 7

如果您处于详细模式,则将 STDOUT 绑定到另一个句柄,否则将这些句柄链接到 /dev/null。然后编写您的脚本,以便可选的东西指向额外的句柄。

#!/bin/sh

exec 6>/dev/null

if [ $# -ge 1 -a "$1" = "--verbose" ]; then
echo    "Verbose mode."
exec 6>&1
fi

echo "Things I want to see regardless of my verbose switch."

#... Other things...

# This command and others along the script should only be seen if I am in verbose mode.
ls -l >&6 2>&1
Run Code Online (Sandbox Code Playgroud)

这应该让你开始。我不确定这是否特定于 BASH。那只是很久以前的回忆。;-)