Redirect stderr and stdout in Bash

后端 未结 15 798
日久生厌
日久生厌 2020-11-22 08:18

I want to redirect both stdout and stderr of a process to a single file. How do I do that in Bash?

15条回答
  •  难免孤独
    2020-11-22 08:45

    @fernando-fabreti

    Adding to what you did I changed the functions slightly and removed the &- closing and it worked for me.

        function saveStandardOutputs {
          if [ "$OUTPUTS_REDIRECTED" == "false" ]; then
            exec 3>&1
            exec 4>&2
            trap restoreStandardOutputs EXIT
          else
              echo "[ERROR]: ${FUNCNAME[0]}: Cannot save standard outputs because they have been redirected before"
              exit 1;
          fi
      }
    
      # Params: $1 => logfile to write to
      function redirectOutputsToLogfile {
          if [ "$OUTPUTS_REDIRECTED" == "false" ]; then
            LOGFILE=$1
            if [ -z "$LOGFILE" ]; then
                echo "[ERROR]: ${FUNCNAME[0]}: logfile empty [$LOGFILE]"
            fi
            if [ ! -f $LOGFILE ]; then
                touch $LOGFILE
            fi
            if [ ! -f $LOGFILE ]; then
                echo "[ERROR]: ${FUNCNAME[0]}: creating logfile [$LOGFILE]"
                exit 1
            fi
            saveStandardOutputs
            exec 1>>${LOGFILE}
            exec 2>&1
            OUTPUTS_REDIRECTED="true"
          else
            echo "[ERROR]: ${FUNCNAME[0]}: Cannot redirect standard outputs because they have been redirected before"
              exit 1;
          fi
      }
      function restoreStandardOutputs {
          if [ "$OUTPUTS_REDIRECTED" == "true" ]; then
          exec 1>&3   #restore stdout
          exec 2>&4   #restore stderr
          OUTPUTS_REDIRECTED="false"
         fi
      }
      LOGFILE_NAME="tmp/one.log"
      OUTPUTS_REDIRECTED="false"
    
      echo "this goes to stdout"
      redirectOutputsToLogfile $LOGFILE_NAME
      echo "this goes to logfile"
      echo "${LOGFILE_NAME}"
      restoreStandardOutputs 
      echo "After restore this goes to stdout"
    

提交回复
热议问题