Home > Enterprise >  How to show error on console while logging it to both log file and console in bash
How to show error on console while logging it to both log file and console in bash

Time:10-07

I am trying to log messages to both console and a log file in a bash script. I am able to log the stdout message both in console and log file but not a stderr. Below is the script and output. Please help.

Script:

!/bin/bash
LOG_FILE='./test1.log'
exec 3>&1 1>>${LOG_FILE} 2>&1
echo "log to console and log file" | tee /dev/fd/3
echo "only to log file"
chmm 777 ${LOG_FILE}

Log file:

log to console and log file
only to log file
./log_to_console_and_file.sh: line 6: chmm: command not found

Console:

log to console and log file

I want the below error message to be shown in the console as well.

./log_to_console_and_file.sh: line 6: chmm: command not found

Thanks.

CodePudding user response:

If I understand well you'd like to send stderr to the console and to the log file, stdout only to the log file, plus be able to send messages both to the log file and the console with echo ... | tee /dev/fd/3.

To send stderr to the console and to the log file simply redirect it to a tee -a "$LOG_FILE" command using process substitution. Then make a copy of stdout to fd3 and redirect (append) stdout to the log file:

#!/usr/bin/env bash

LOG_FILE='./test1.log'
exec 2> >( tee -a "$LOG_FILE" ) 3>&1 1>>"$LOG_FILE"

echo "log to console and log file" | tee /dev/fd/3
echo "only to log file"
chmm 777 ${LOG_FILE}

Demo:

$ ./log_to_console_and_file.sh
log to console and log file
./log_to_console_and_file.sh: line 8: chmm: command not found
$ cat test1.log 
log to console and log file
only to log file
./log_to_console_and_file.sh: line 8: chmm: command not found

Of course you know already that the order of redirections matters.

Note that your shebang (!/bin/bash) is incorrect. Note also that as stderr now appends to console and log file you don't really need fd3 any more. To send something to console and log file you could probably simply redirect it to stderr...

  • Related