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!
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.
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:"
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.
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.
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
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With