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.