Need a way to temporarily redirect STDOUT


Need a way to temporarily redirect STDOUT



I know how to redirect output in Linux. Thing is, I have alot of output in my bash script and I don't want to type something like


echo $foo >> bar



over and over again. I would much 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 opening FD 1 as a file:


exec 1>bar



but couldn't get STDOUT back to normal when I was done. Closing the file


exec 1>&-



gave me errors that I couldn't get around.



Any way to do this? Thanks!




3 Answers
3



You have to first save stdout (by linking it on fd #4 for instance)



exec 4<&1



Redirect stdout



exec 1>bar



And restore saved stdout



exec 1<&4





OK, learned something new about file descriptors here. Any references on what it means to 'save' stdout (or another file descriptor)? Thanks!
– bob.sacamento
Nov 5 '12 at 19:27





See dup2 pubs.opengroup.org/onlinepubs/009695399/functions/dup2.html
– Andrew Tomazos
Nov 5 '12 at 20:41


dup2





Also, close fd 4 with exec 4<&- when done with it.
– Kusalananda
Jul 1 at 7:24


exec 4<&-



There are likely several ways to do what you want, but probably the easiest would be a subshell or command group:


( some
commands
you
want
to
redirect ) >> logfile



The ( ... ) construct is a subshell; using { ... } is slightly lighter weight as it's just a group of commands. Which to prefer would depend on whether you want variables assigned inside the group to persist afterwards, primarily, although there are a couple other differences as well...


( ... )


{ ... }





Thanks! That might do it.
– bob.sacamento
Nov 5 '12 at 19:27





Commands inside a subshell are run as in a non-interactive shell which is also why a { block; } is preferred.
– Tom Hale
Jun 30 at 9:13



{ block; }



The simplest way is:


{
echo "ALL THE THINGS"
} > OUTFILE


function verbose() {
local tmp stdout;
exec {stdout}>&1 {tmp}>>OUTFILE # Save STDOUT; append to OUTFILE
exec >&$tmp {tmp}>&- # dup tmp to STDOUT; close tmp
echo "ALL THE THINGS"
exec >&$stdout- # Restore STDOUT, close placeholder
}



Above, the echo will also go into OUTFILE.


echo


OUTFILE






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Extract Id from Twitch Clip URL

Why are these constructs (using ++) undefined behavior in C?

I'm Still Waiting (Diana Ross song)