管道 bash stdout 仅在 "debug" 模式下
Pipe bash stdout only in "debug" mode
我正在努力实现这一目标:
PIPE=""
if [ $DEBUG = "true" ]; then
PIPE="2> /dev/null"
fi
git submodule init $PIPE
但是 $PIPE
被解释为 git 的命令行参数。如何仅在调试模式下显示 stdout
和 stderr
,而在非调试模式下仅显示 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}"
首先我猜你的逻辑是错误的,如果 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
在 >
之后使用变量
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>&-
我正在努力实现这一目标:
PIPE=""
if [ $DEBUG = "true" ]; then
PIPE="2> /dev/null"
fi
git submodule init $PIPE
但是 $PIPE
被解释为 git 的命令行参数。如何仅在调试模式下显示 stdout
和 stderr
,而在非调试模式下仅显示 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}"
首先我猜你的逻辑是错误的,如果 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
在 >
之后使用变量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>&-