我正在尝试实现这一点:
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}"
在>后使用变量
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