此代码片段来自Advanced Bash Scripting Guide。
# Redirecting only stderr to a pipe.
exec 3>&1 # Save current "value" of stdout.
ls -l 2>&1 >&3 3>&- | grep bad 3>&- # Close fd 3 for 'grep' (but not 'ls').
# ^^^^ ^^^^
exec 3>&- # Now close it for the remainder of the script.
# Thanks, S.C.
Run Code Online (Sandbox Code Playgroud)
注释解释了代码只为“grep”关闭 fd 3。但关闭 fd 3 两次。为什么我们需要这样做?像这样为“grep”只关闭一次 fd 3 是错误的吗?
ls -l 2>&1 >&3 | grep bad 3>&-
Run Code Online (Sandbox Code Playgroud)