bash: how to redirect stdin/stderr then later revert fd's?

断了今生、忘了曾经 提交于 2019-12-04 05:11:14

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

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).

HTH

It seems pretty clean to me. The only thing I'd to is to pass the "outfile" name as a parameter to the function, since you use the filename outside of the function

redirect() {
    exec 3>&1
    exec 4>&2
    exec 1>"$1" 2>&1
}
:
redirect outfile
:
if some_predicate outfile; ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!