Skip to content
Advertisement

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

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:

JavaScript

Log file:

JavaScript

Console:

JavaScript

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

JavaScript

Thanks.

Advertisement

Answer

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:

JavaScript

Demo:

JavaScript

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement