仅在“调试”模式下管理bash stdout

我试图达到这个目的:

PIPE=""
if [ $DEBUG = "true" ]; then
    PIPE="2> /dev/null"
fi
git submodule init $PIPE

$PIPE被解释为命令行参数。 如何仅在调试模式下显示stdoutstderr ,而在非调试模式下只管理stderr


感谢伟大的见解。 如果不在调试模式下,将所有内容重定向到/ dev / null,并在调试模式下打印stderr和stdout:

# debug mode
if [[ ${DEBUG} = true ]]; then
    PIPE=/dev/stdout
else
    PIPE=/dev/null
fi

git submodule init 2>"${PIPE}" 1>"${PIPE}"

>后使用变量

if [[ ${DEBUG} = true ]]; then
    errfile=/dev/stderr
else
    errfile=/dev/null
fi

command 2>"${errfile}"

修改文件描述符

您可以将stderr复制到新的文件描述符3

if [[ ${DEBUG} = true ]]; then
    exec 3>&2
else
    exec 3>/dev/null
fi

然后为每个要使用新重定向的命令

command 2>&3

关闭fd 3,如果不再需要

exec 3>&-

首先,我猜你是逻辑错了,DEBUG = true,你会发送stderr到/ dev / null。 此外,你的字符串比较缺少第二个“=”,

简单的解决方案如何?

if [ "${DEBUG}" == "true" ]; then
    git submodule init
else
    git submodule init  2>/dev/null
fi

在您的回复中编辑:

或者你可以使用eval ,但要小心它被认为是邪恶的;)

if [ "${DEBUG}" == "true" ]; then
    PIPE=""
else
    PIPE="2>/dev/null" 
fi 
eval git submodule init $PIPE
链接地址: http://www.djcxy.com/p/77103.html

上一篇: Pipe bash stdout only in "debug" mode

下一篇: How to redirect both stdout and stderr to a file