I have a situation wherein I want to send error and log messages to a same file. To distinguish between the error and log message开发者_如何学Cs I am appending the log messages like this :
file would look like this :
===============log_and_error_msg.txt =========
ERR: This message is an error message
INF: This is a log message
so that anybody interested in error messages can grep "ERR" log_and_error_msg.txt
suppose I am executing some shell script like this
./shellscript 2>>log_and_error_msg.txt 1>>log_and_error_msg.txt
How do I add ERR and INF on fly to each message on fly ??
#!/bin/bash
exec 3> >(sed 's/^/INF: /' >> prepend.log)
exec 4> >(sed 's/^/ERR: /' >> prepend.log)
echo "some information" >&3
echo "an error" >&4
echo "more information" >&3
echo "this goes to the screen"
echo "this goes to stderr, bypassing the log" >&2
echo "another error" >&4
echo "yet more information" >&3
echo "still information" >&3
echo "oops" >&4
You can use sed. Insert sed 's/^/TYPE /'
in each pipeline, replacing TYPE with ERR:
or INF:
Try redirecting stderr to a temporary file.
./testscript.sh 2> err.tmp | ( while read line ; do echo 'INFO: ' $line ; done ) ; ( while read line ; do echo 'ERR: ' $line ; done ) <err.tmp
{ { ./shellscript | sed 's/^/INF: /'; } 2>&1 1>&3 | sed 's/^/ERR: /'; } \ >> log_and_error_message.txt 3>&1
精彩评论