Adding custom message to exec 1 in shell scripting

Viewed 219

I want to add a filtered text to every STDOUT goes to a log file. Example : echo "custome message' exec 1 >> log file. However its no working.I have separate custom messages for STDOUT and STDERR. For STDOUT I need to add message as "INFORMATION" For STDERR I need to add message as "ERROR" And all the messages to be added to same file for STDOUT: custom message 1 + STDOUT > logfile for STDERR: custom message 2 + STDERR > logfile

Any suggestion on it

1 Answers

Consider this script file:

$ cat script.sh
#!/bin/bash
exec > >(awk -v msg="Custom Message: " '{print msg,$0}' >file.log)
echo Out 1
echo More output
echo Last bit of output

We can run it and then look at the log file:

$ bash script.sh
$ cat file.log
Custom Message:  Out 1
Custom Message:  More output
Custom Message:  Last bit of output

>(awk -v msg="Custom Message: " '{print msg,$0}' >file.log) is an example of process substitution. It acts like a file that we can write to and thus is suitable for the object of the redirection command exec >. The awk command prepends the custom message to every line of output.

process substitution requires bash or other advanced shell.

Separate messages for stdout and stderr

This script processes stdout and stderr and then sends each to file handle 3 which is written to file file.log:

$ cat script.sh
#!/bin/bash
exec 3>file.log
exec > >(awk -v msg="Custom Message: " '{print msg,$0}' >&3) 2> >(awk -v msg="Error: " '{print msg,$0}' >&3)
echo Out 1
echo Some error message >&2
echo More output
echo Last bit of output

Here is a sample run and resulting log file:

$ bash script.sh
$ cat file.log
Error:  Some error message
Custom Message:  Out 1
Custom Message:  More output
Custom Message:  Last bit of output

Note that the stderr and stdout messages may appear out of order relative to each other. This is an inevitable result of the multitasking required when processing each separately and then recombining.

Related