需要一种临时重定向STDOUT的方法

bob*_*nto 12 linux bash redirect

我知道如何在Linux中重定向输出.事实是,我的bash脚本中有很多输出,我不想输入类似的东西

echo $foo >> bar
Run Code Online (Sandbox Code Playgroud)

一遍又一遍地.我宁愿做类似的事情:

hey, bash, for the time being put all your STDOUT in "bar"
echo $foo
.
.
OK, bash, you can go back to regular STDOUT now
Run Code Online (Sandbox Code Playgroud)

我尝试将FD 1作为文件打开:

exec 1>bar
Run Code Online (Sandbox Code Playgroud)

但是当我完成时,无法使STDOUT恢复正常.关闭文件

exec 1>&-
Run Code Online (Sandbox Code Playgroud)

给了我一些我无法解决的错误.

有什么办法吗?谢谢!

小智 17

你必须先保存标准输出(例如通过在fd#4上链接它)

执行4 <&1

重定向标准输出

执行1>吧

并恢复保存的标准输出

执行1 <&4


twa*_*erg 7

有几种方法可以做你想要的,但最简单的可能是子shell或命令组:

( some
  commands
  you
  want
  to
  redirect ) >> logfile
Run Code Online (Sandbox Code Playgroud)

( ... )构造是一个子壳; 使用{ ... }稍微轻一点,因为它只是一组命令.哪个更喜欢取决于你是否希望在组内分配的变量在之后保持,主要是,尽管还有其他一些差异......