庆典:如何重定向标准输入/标准错误后来恢复FD的? [英] bash: how to redirect stdin/stderr then later revert fd's?

查看:128
本文介绍了庆典:如何重定向标准输入/标准错误后来恢复FD的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个脚本标准输入和stderr重定向到一个文件,做了一堆东西,然后撤消这些重定向,并就文件的内容采取行动。我想:

I want a script to redirect stdin and stderr to a file, do a bunch of stuff, then undo those redirections and take action on the file contents. I'm trying:

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

这似乎做我想做的,但似乎相当复杂。是否有一个更清洁/更清晰的方式做到这一点?

Which seems to do what I want, but it seems rather complex. Is there a cleaner/clearer way to do this?

推荐答案

如果你真的需要切换来回,事先不知道究竟会去哪里时,这是pretty很多工作要做,它的方式。根据您的要求,虽然它可能是整洁到需要重定向的部分隔离,并执行它们作为组,就像这样:

If you really need to switch it back and forth, without knowing beforehand what will go where and when, that's pretty much the way to do it. Depending on your requirements though it might be neater to isolate the parts which need redirecting, and execute them as group, like so:

echo first
{
  echo something
  cat kjkk
} 1>outfile 2>&1
if some_predicate outfile; then echo ERROR; fi

{} 被称为一组命令,从整个集团的输出重定向。如果preFER,你可以做一个子shell的高管,因为它仅影响子shell。

the {} is called a group command, and the output from the entire group is redirected. If you prefer, you can do your execs in a subshell, as it only affects the subshell.

echo first
(
  exec 1>outfile 2>&1

  echo something
  cat kjkk
)
if some_predicate outfile; then echo ERROR; fi

请注意,我使用括号()在这里,而不是括号 {} (这是在使用的第一个例子)。

Note that I'm using parentheses () here, rather than braces {} (which were used in the first example).

心连心

这篇关于庆典:如何重定向标准输入/标准错误后来恢复FD的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆