Tracing a function call

Hi

I am hoping someone can explain this to me as I am struggling to understand it.

I had a problem today with needing to trace a ksh script that was dotting in a function that was writing to stdout. The problem was it was being run in a sub shell and the output was being parsed by the calling script so I could not have any trace output on stdout.

On a hunch I tried this solution to log the function's trace to file and it worked but I don't know why, can anyone enlighten me?

The code: -

TX5XN:/home/brad/ksh_stuff>cat trace_2

func()
{
    set -x
    echo "This goes to stdout from func"
    set +x
    echo "=============================" >&2
} 2>> set.log2

echo "This goes to stdout from main body"

for x in 1 2 3 4 5
do
    func
done

The output to stdout: -

TX5XN:/home/brad/ksh_stuff> trace_2  
This goes to stdout from main body
This goes to stdout from func
This goes to stdout from func
This goes to stdout from func
This goes to stdout from func
This goes to stdout from func

The trace log: -

TX5XN:/home/brad/ksh_stuff>cat set.log2
trace_2:5-echo 'This goes to stdout from func'
=============================
trace_2:5-echo 'This goes to stdout from func'
=============================
trace_2:5-echo 'This goes to stdout from func'
=============================
trace_2:5-echo 'This goes to stdout from func'
=============================
trace_2:5-echo 'This goes to stdout from func'
=============================

Hi:

Your code redirects stderr for the function to set.log2, so that's where all the trace output will be found. If the calling script is only reading stdout (from a pipe or coprocesses or fifo), you don't need that redirection.

-- Shell Command Language

Regards,
Alister