Search code examples
bashechostdoutstderrio-redirection

redirect output to terminal


I am trying to understand redirecting the output.

I have the code:

#!/bin/bash
function function1 () {
    log=${1}.log

    exec 3>&1
    exec 1>>$log
    exec 2>&1

    echo checking $log >&3
    echo txt to $log
}

function1 log1
function1 log2

exit 0

the output that I get is:

checking log1.log

and file log1.log with content

txt to log1.log
checking log2.log

and file log2.log with content

txt to log2.log

what I really want is file log1.log with content

txt to log1.log

and file log2.log with content

txt to log2.log

and output to terminal to be.

checking log1.log
checking log2.log

How can I do that, please ? I know I can use function1 log1 > log1.log 2>&1, but than I can not redirect echo back to terminal in function1, I can but it is similar result.


Solution

  • If you want to set stdout and stderr and then restore them in the function do:

    function function1 () {
        log=${1}.log
        exec 4>&2 3>&1 1>>$log 2>&1 # save 1 and 2 to 3 and 4
        echo checking $log >&3
        echo txt to $log
        exec 1>&3 2>&4 3>&- 4>&- # restore 1 and 2
    }
    

    The 3>&- closes 3, just for completeness.