gpt4 book ai didi

linux - 尝试在bash中使用变量将stderr重定向到/dev/null

转载 作者:太空宇宙 更新时间:2023-11-04 04:11:00 24 4
gpt4 key购买 nike

这就是我正在尝试做的事情:

[[ "${1}" == "debug" ]] && DEBUG='2>/dev/null' || DEBUG=''

{
echo "a b c"
echo "d e f" >&2
} ${DEBUG}

这不起作用,因为“sh:意外标记‘${BLAH}’附近有语法错误”。我能够做类似的事情,如下所示:

eval echo "def" ${DEBUG}

但我无法用一大块代码来做到这一点。另一种方法可能是使用“exec”与我的代码的其余部分一起进行重定向,例如:

[[ "${1}" == "debug" ]] && exec 2>/dev/null

但是如果我尝试以特定方式使用 exec,我的 shell 就会挂起。刀友们有什么想法吗?

最佳答案

创建另一个文件描述符:

[[ "${1}" == "debug" ]] && exec 7>/dev/null || exec 7>&2

{
echo "a b c"
echo "d e f" >&7
}

顺便问一下,当提到 debug 参数时,你确定输出应该被取消吗?

实际上更好的方法是创建一个函数:

if [[ "${1}" == "debug" ]]; then
function debug {
echo "$1" >&2
}
else
function debug {
:
}
fi

{
echo "a b c"
debug "d e f"
}

关于linux - 尝试在bash中使用变量将stderr重定向到/dev/null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19060692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com