Redirect stdout and stderr to Function

后端 未结 6 1286
滥情空心
滥情空心 2020-12-25 14:07

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 follow

6条回答
  •  太阳男子
    2020-12-25 14:41

    Thanks to people who posted their responses. I came up with my version which will add timestamp once per message.

    #!/bin/bash
    CURRENT_PID=$$
    PROCESS_NAME=$(basename $0)
    
    LOGFILE=/var/log/backup-monitor.log
    function log_message {
      if [ -n "$1" ]; then
          MESSAGE="$1"
          echo -e "$(date -Iseconds)\t$PROCESS_NAME\t$CURRENT_PID\t$MESSAGE" | tee -a $LOGFILE
      else
          MESSAGE=$(tee)
          echo -e "$(date -Iseconds)\t$PROCESS_NAME\t$CURRENT_PID\t$MESSAGE" | tee -a $LOGFILE
      fi
    }
    
    log_message "Direct arguments are working!!"
    
    echo "stdin also working" | log_message
    

提交回复
热议问题