Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout and stderr to Function

Tags:

I need help sending the output (stdin and stdout) from system commands to a bash function, while still accepting input from arguments. Something like the example that follows. Can someone point me down the right road?

LogMsg() {   DateTime=`date "+%Y/%m/%d %H:%M:%S"`   echo '*****'$DateTime' ('$QMAKESPEC'): '$1 >> "$LogFile"   echo $DateTime' ('$QMAKESPEC'): '$1 }  # Already works LogMsg "This statement is sent directly"  # Wish I could do this: # Capture both stdout & stderr of a system function to the logfile # I do not presume that any of the syntax that follows is good make 2>&1 >(LogMsg) 
like image 222
Ryan Avatar asked Aug 10 '12 15:08

Ryan


People also ask

How can I redirect stdout and stderr in same location?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

What is the meaning of 2 >& 1 in Linux?

1 "Standard output" output file descriptor. The expression 2>&1 copies file descriptor 1 to location 2 , so any output written to 2 ("standard error") in the execution environment goes to the same file originally described by 1 ("standard output").


1 Answers

To do this you can use the read bash builtin:

LogMsg() {   read IN # This reads a string from stdin and stores it in a variable called IN   DateTime=`date "+%Y/%m/%d %H:%M:%S"`   echo '*****'$DateTime' ('$QMAKESPEC'): '$IN >> "$LogFile"   echo $DateTime' ('$QMAKESPEC'): '$IN } 

And then use a pipe:

make 2>&1 | LogMsg 

Update:

To be able to use stdin OR an argument as input (as per chepner's comment) you can do this:

LogMsg() {   if [ -n "$1" ]   then       IN="$1"   else       read IN # This reads a string from stdin and stores it in a variable called IN   fi    DateTime=`date "+%Y/%m/%d %H:%M:%S"`   echo '*****'$DateTime' ('$QMAKESPEC'): '$IN >> "$LogFile"   echo $DateTime' ('$QMAKESPEC'): '$IN } 
like image 143
Lee Netherton Avatar answered Sep 22 '22 18:09

Lee Netherton