In Unix shell, I have a env file (env file defines the parameters required for running the user script like log file name and path, redirect outputs and errors to log file, database connection details, etc) which redirects all the outputs (echo messages) and errors to the log file from the executed script using the following code:
exec 1>>${LOG_FILE}
exec 2>>${LOG_FILE}
The env file is executed at the beginning of each script. Due to the above code in env file all the console outputs that might be user outputs or errors are directly output to the log file which is what I actually needed.
But there are some selective user outputs which I want to be displayed in both the console and the log file. But because of the above code I am not able to do so.
I know that if I remove the above code I can get the desired result for this case, but I will have to manually write all other outputs to the log file which is not an easy task.
Is there a way to get the output in both the console and the log file without removing the above codes?
I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:
Then in the actual script I have the following codes:
Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.
After executing the above script file I have following outputs:
In console
For the Log file
Hope this help.
would send stdout and stderr output into the log file, but would also leave you with fd 3 connected to the console, so you can do
to write a message just to the console, or
to write a message to both the console and the log file -
tee
sends its output to both its own fd 1 (which here is theLOG_FILE
) and the file you told it to write to (which here is fd 3, i.e. the console).Example:
would print
on the console and put
into the log file.
I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:
Add following lines at the top of your script:
Hope this helps somebody!
Yes, you want to use
tee
:Just pipe your command to tee and pass the file as an argument, like so:
This both prints the output to the STDOUT and writes the same output to a log file. See
man tee
for more information.Note that this won't write stderr to the log file, so if you want to combine the two streams then use:
I tried joonty's answer, but I also got the
error. This is what works best for me (confirmed to work in zsh also):
The file /tmp/both.log afterwards contains
The /tmp/both.log is appended unless you remove the -a from tee.
Hint:
>(...)
is a process substitution. It lets theexec
to thetee
command as if it were a file.