I'm trying to log some part of script execution. Logs should be displayed at second tty, and also written to a log file.
I can do it with a simple:
echo "Hello log" > /dev/tty2
echo "Hello log" > /var/log/my_logs
But it is very uncomfortable. I could also redirect echo to a particular place:
exec 1<>/var/log/my_logs
exec 2>&1
But how can I redirect STDOUT to both /dev/tty2 and /var/log/my_logs at once?
Redirecting output to Multiple files and screen: If you want to redirect the screen output to multiple files, the only thing you have to do is add the file names at the end of the tee command.
For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.
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.
Use tee
.
echo "Hello log" | tee /dev/tty2 /var/log/my_logs > /dev/null
(The final redirection is to prevent the output from appearing to standard output as well. You could also use echo "Hello log" | tee /dev/tty2 > /var/log/my_logs
; there's no real difference between the two. tee
just writes it standard input to both standard output and one or more named files.)
To redirect all of standard output to the pair, use a process substitution with exec
.
exec > >(tee /dev/tty2 /var/log/my_logs)
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