Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 580
bob.sacamento Avatar asked Nov 05 '12 19:11

bob.sacamento


People also ask

How do I redirect stdout?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

What does it mean to redirect to 2 >& 1?

So when you use 2>&1 you are basically saying “Redirect the stderr to the same place we are redirecting the stdout”. And that's why we can do something like this to redirect both stdout and stderr to the same place:"

What does it mean to redirect stdout output?

Redirection is a feature in Linux such that when executing a command, you can change the standard input/output devices. The basic workflow of any Linux command is that it takes an input and give an output. The standard input (stdin) device is the keyboard. The standard output (stdout) device is the screen.

How would you redirect a command stderr to stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


2 Answers

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

like image 64
vladz Avatar answered Oct 18 '22 09:10

vladz


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

like image 34
twalberg Avatar answered Oct 18 '22 08:10

twalberg