Need STDOUT Temporary Redirection Method

I know how to redirect output to Linux. The thing is, I have a lot of output in my bash script, and I don't want to enter something like

echo $foo >> bar 

again and again. I would rather do something like:

 hey, bash, for the time being put all your STDOUT in "bar" echo $foo . . OK, bash, you can go back to regular STDOUT now 

I tried to open FD 1 as a file:

 exec 1>bar 

but I could not return STDOUT to normal when it was done. File closing

 exec 1>&- 

gave me errors that I could not get around.

How to do it? Thanks!

+7
source share
2 answers

You must first save stdout (e.g. binding it to fd # 4)

exec 4 <& 1

Redirect stdout

exec 1> bar

And restore the saved stdout

exec 1 <& 4

+15
source

There are probably several ways to do what you want, but probably the subordinate or team group will be the simplest:

 ( some commands you want to redirect ) >> logfile 

The construction ( ... ) is a subshell; using { ... } little easier, as it is just a group of commands. Which is preferable will depend on whether you want the variables assigned within the group to be saved subsequently, first of all, although there are other differences ...

+6
source

All Articles