1

I have 2 log functions:

log_msg()
{
    if [ ! -e $LOG_FILE ]; then
        touch $LOG_FILE
        chmod 0640 $LOG_FILE
    fi

    echo "$(date +'[%Y-%m-%d %T]') $1" >> $LOG_FILE
}
log_stream()
{
    while read data; do
        printf "$(date +'[%Y-%m-%d %T]') $data" >> $LOG_FILE
    done
}

In order to log msg:

log_msg "Hello World!";

In order to log stdout of another function I tried to do:

bgcommand --a --b 2>&1 > log_stream &

But it's not working.

I've found the function to log pipe at this question: Pipe output to bash function But something is missing.

Community
  • 1
  • 1
Max Cuttins
  • 614
  • 2
  • 6
  • 20
  • 1
    If you are using `bash` 4.2, you can avoid invoking `date` by using `printf '%([%Y-%m-%d %T])T %s\n" "$1"`. – chepner Jul 30 '15 at 15:53

1 Answers1

7

You are writing to a file named "log_stream". The shell is not looking for a program/function name there. Try this:

bgcommand --a --b 2>&1 | log_stream &
#......................^

Or, redirect to a process substitution

bgcommand --a --b 2>&1 > >(log_stream) &

You might want to look into a utility named ts whose purpose is to add timestamps to it's input.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Seems ok use the "|". But I decided to do not use it because this should affect "&" modificator and send only "log_stream" command in background instead of "bgcommand". Can you confirm that use "|" will not affect the "&" only on last command in the pipe? – Max Cuttins Jul 30 '15 at 14:49
  • 2
    `&` will send the whole pipeline into the background – glenn jackman Jul 30 '15 at 14:53