bash:如何重定向stdin/stderr然后再恢复fd?

Geo*_*ung 7 bash redirect descriptor

我想要一个脚本将stdin和stderr重定向到一个文件,做一堆东西,然后撤消那些重定向并对文件内容采取行动.我尝试着:

function redirect(){
   exec 3>&1
   exec 4>&2
   exec 1>outfile 2>&1
}
function undirect(){
   exec 1>&3
   exec 2>&4
}
echo first
redirect
echo something
cat kjkk
undirect
if some_predicate outfile; then echo ERROR; fi
Run Code Online (Sandbox Code Playgroud)

这似乎做我想要的,但似乎相当复杂.是否有更清洁/更清晰的方法来做到这一点?

fal*_*tro 8

如果你真的需要来回切换它,而不事先知道将在何时何地发生,这几乎就是这样做的方式.根据您的要求,尽管隔离需要重定向的部件并将其作为组执行可能更为简洁,如下所示:

echo first
{
  echo something
  cat kjkk
} 1>outfile 2>&1
if some_predicate outfile; then echo ERROR; fi
Run Code Online (Sandbox Code Playgroud)

{}被称为一组命令,并且从整个组输出被重定向.如果您愿意,可以在子shell中执行您的执行,因为它只会影响子shell.

echo first
(
  exec 1>outfile 2>&1

  echo something
  cat kjkk
)
if some_predicate outfile; then echo ERROR; fi
Run Code Online (Sandbox Code Playgroud)

请注意,我在()这里使用括号,而不是括号{}(在第一个示例中使用).

HTH