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)
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.
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").
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With