1

I have a script like the following

function long_proc()
{
    #script1 that generate output1
    #script2 that generate output2
    ....
}

long_proc > /tmp/debug.log

My requirement is the complete log should divert to /tmp/debug.log where as the output of script2 should go to stdout as well as to the log file.

can any one help me?

shafeeq
  • 1,499
  • 1
  • 14
  • 30
  • `long_proc > /tmp/debug.log 2>&1`? – Cyrus Jul 12 '16 at 12:39
  • 1
    @cyrus, it will output complete log to the file as well as stdout, right? But my requirement is some what different. the output of some command need to be diverted into stdout. – shafeeq Jul 12 '16 at 12:57
  • 1
    When you say should go to `stdout` do you mean `stdout` or the terminal ? – 123 Jul 12 '16 at 13:00

1 Answers1

2

So this is what i think you want to do.

To keep output on stdout but also go to file

long_proc(){

    exec 4>&1
    #redirect fd4(currently nothing hopefully) to stdout

    exec 1>&3
    #redirect stdout to fd3(also hopefully unused)
    #Note you have 5 more to choose from if they are in use.


    echo Just log
    #script1 that generate output1

    echo Log and Stdout | tee >(cat - >&4)
    #script1 that generate output2
    # Tee into a subproc to cat data into fd4 pointing to stdout
    #The tee'd data also goes to fd3

    exec 1>&4
    # set fd1 back to stdout

    exec 4>&-
    #close fd4

}

long_proc 3> log
#Send fd3 to log, stdout is untouched and does whatever you want.

So redirect all output to fd3, which is then all piped into log. Tee into stdout anything that you want to also be in stdout.

Benefit of this is that you can then pipe like

long_proc 3> log | sed 's/^/Piped and /'
123
  • 10,778
  • 2
  • 22
  • 45
  • 1
    Your two `exec` statements affect the shell from which `long_proc` is called; they are not local to the body of the function. You should either use a subshell as the body (`long_proc () ( ... )`), or restore the file descriptors before exiting. – chepner Jul 12 '16 at 13:34
  • can you add some explanation about 4>&1..?? – shafeeq Jul 12 '16 at 13:41
  • @shafeeq Added explanations. – 123 Jul 12 '16 at 13:47