Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout and stderr to file permanently but keep printing them

Tags:

bash

By doing the following(1):

 exec >> log_file
 exec 2>&1
 ls

stdout and stderr is permanently redirected for the next commands but not anymore displayed on terminal. Here, ls output will be in log_file but not displayed in terminal

By doing the following(2):

command | tee log_file

command output will be both in log_file and printed on terminal but this will work only for command and not for the next commands as method 1.

How to redirect permanently stdout and stderr output in a file for a given terminal like method 1 and, keep stdout and stderr printed on the terminal instance like method 2 ?

like image 424
Thomas Kostas Avatar asked Oct 26 '25 03:10

Thomas Kostas


1 Answers

I currently use this in my scripts:

exec > >(tee -a "${FILE_Log}" )
exec 2> >(tee -a "${FILE_Log}" >&2)

Basically you are telling bash to send the output (both stdout and stderr) to tee's stdin, and since tee is running in the subshell (within the parentheses), it will live as long as your script does.

Put that somewhere near the top, then any and all command output, echo, print, and, printf will be logged.

This saves having to create a LOG() function and constantly piping commands to tee

Hope that helps!

like image 143
Hickory420 Avatar answered Oct 29 '25 07:10

Hickory420



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!