当shopt -s autocd
我导航到任何文件夹(例如文件~/Projects
夹)时,我会cd ~/Projects
进入终端输出,然后移动到~/Projects
。我怎样才能隐藏刚刚执行的输出shopt
?(cd ~/Projects
事情):
答案1
此输出(以及许多其他自动生成的 Bash 输出)被发送到 set -x 使用的相同文件描述符,因此您可以使用:
exec {BASH_XTRACEFD}>/dev/null
将其重定向到
/dev/null
。然而,这似乎将文件描述符泄漏到所有执行的进程中,这可能是不可取的。(我对此感到有点惊讶……我原以为 BASH_XTRACEFD 文件描述符会被标记为 close-on-exec。)
我发现这里但我不确定这种重定向的后果,也不知道如何逆转它
答案2
如果有人想使用BASH_XTRACEFD
重定向技巧,但保留的行为set -x
,这就是我所做的:
shopt -s autocd
# silence_autocd
# - Hack to stop autocd from printing the directory after autocd'ing.
# - Unfortunately there is no clean way to do this except messing with
# BASH_XTRACEFD, a poorly understood file descriptor that we are better not
# to mess with, yet here we are.
# - Warning: This might break things, so try disabling it if something looks
# off.
silence_autocd() {
exec {BASH_XTRACEFD}>/dev/null
}
silence_autocd
# unsilence_autocd
# - Needed to undo the above temporarily.
# - Unfortunately, BASH_XTRACEFD is used for other things besides autocd.
# - In those cases, I need to undo and redo the redirection.
# - Currently "set -x" is the only notable user of BASH_XTRACEFD that I've
# found so far, but there could be others in the future.
# - For the time being, I pray to the Bash Gods to provide a native way to
# disable autocd printing soon.
unsilence_autocd() {
exec {BASH_XTRACEFD}>/dev/stdout
}
# custom set
function set () {
# if calling "set -x", undo the silencing of autocd
if [[ "$#" == 1 && "$1" == "-x" ]]; then
command set -x;
unsilence_autocd;
elif [[ "$#" == 1 && "$1" == "+x" ]]; then
silence_autocd;
command set +x;
else
command set "$@";
fi;
}