Search code examples
bashfunctionloggingtee

why won't Tee write all output being given (Bash)?


I've run into a problem which I don't know the cause of. I guess the easiest way to explain is by a code example:

test ()
{
    echo "This will be printed to the file"

    #But the output of rsync will not
    rsync -av /path/A /path/B

    echo "This will be printed to the file"
}

function_calling_test ()
{
    test | tee -a "file_B.txt"
}

function_calling_test | tee -a "file_A.txt"

In the above example file_A.txt will contain both echo output and the rsync output from the function "test", but file_B.txt will only contain the echo output. Why is this?


Solution

  • You need to add the stderr output to the stream

    mytest ()
    {
        echo "This will be printed to the file"
    
        #But the output of rsync will not
        rsync -av /path/A /path/B 2>&1
        # -----------------------^^^^^^
    
        echo "This will be printed to the file"
    }
    

    test is a command available to all unix shells that is part of the unix/Linux OS. Don't name your functions just plain test, you're setting yourself up for an accident! ;-)

    I hope this helps.