Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash redirect output to tty and file

Tags:

bash

stdout

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?

like image 548
Dejwi Avatar asked Sep 03 '14 13:09

Dejwi


People also ask

Can we redirect the output of a command to a file and display at the same time?

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.

How do I redirect a output to a file in bash?

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.

How do I redirect output from stdout to a file?

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.


1 Answers

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)
like image 147
chepner Avatar answered Nov 14 '22 21:11

chepner