Search code examples
bashloggingshstdoutstderr

Bash script - Modify output of command and print into file


Im trying to get text output of specified command, modify it somehow (e.g. add prefix before output) and print into file (.txt or .log)

LOG_FILE=...
LOG_ERROR_FILE=..
command_name >> ${LOG_FILE} 2>> ${LOG_ERROR_FILE}

I would like to do it in one line to modify what command will return and print it into files. The same situation for error output and regular output.

Im beginner in bash scripts, so please be understading.


Solution

  • Create a function to execute commands and capture sterr an stdout to variables.

    function execCommand(){
      local command="$@"
      {
        IFS=$'\n' read -r -d '' STDERR;
        IFS=$'\n' read -r -d '' STDOUT;
      } < <((printf '\0%s\0' "$($command)" 1>&2) 2>&1)
    }
    
    function testCommand(){
        grep foo bar
        echo "return code $?"
    }
    
    execCommand testCommand
    echo err: $STDERR
    echo out: $STDOUT
    
    execCommand "touch /etc/foo"
    echo err: $STDERR
    echo out: $STDOUT
    
    execCommand "date"
    echo err: $STDERR
    echo out: $STDOUT
    

    output

    err: grep: bar: No such file or directory
    out: return code 2
    err: touch: cannot touch '/etc/foo': Permission denied
    out:
    err:
    out: Mon Jan 31 16:29:51 CET 2022
    

    Now you can modify $STDERR & $STDOUT

    execCommand testCommand &&  { echo "$STDERR" > err.log; echo "$STDOUT" > out.log; }
    

    Explanation: Look at the answer from madmurphy