6

I have a bash script that has a few functions which are all called within 1 function. How can I pipe all the output from all the functions up to the main one? I'll be using tee as well to display that output to term and to a log file.

func 1

func 2

func 3
    func 1

func 4 
    func 2
    func 3


call func 4 # i want to grab it here
2
  • I'm having a hard time understanding the question. Output goes to standard output or standard error regardless of how many shell functions or real commands are involved. You can already direct it into a pipeline from the "main one". What does it even mean to "pipe" output from shell functions "up to the main one"? Commented Sep 22, 2010 at 13:36
  • Well, I'm using tee to log the output as well as display it in term. The problem is, one of the functions calls an external script, and none of that output is being logged. The only way I've been able to log it is if I direct and tee the output on that one specific call to the script. If I try to log it in both locations, the file is locked and doesn't work correctly. Commented Sep 22, 2010 at 13:38

3 Answers 3

9

Hmm, when in doubt, use ( ) which will run a subshell and redirect its entire output.

So, try something like:

( mytoplevelfunc ) | tee whatever
Sign up to request clarification or add additional context in comments.

Comments

5

As DigitalRoss said, all stdout goes to the same place and piping and teeing works regardless of how deeply functions and scripts are nested (up to system limits). In the demo below, function f4 demonstrates one way of doing it and f5 demonstrates another.

$ f1 () { echo f1; }
$ f2 () { echo f2; }
$ f3 () { echo f3; f1; }
$ f4 () { echo f4; f2; f3; }
$ f4
f4
f2
f3
f1
$ f4 | tee tee.out
f4
f2
f3
f1
$ cat tee.out
f4
f2
f3
f1
$ f5 () { { echo f4; f2; f3; } | tee tee2.out; }
$ f4 | tee tee.out
f4
f2
f3
f1
$ cat tee.out
f4
f2
f3
f1

Comments

0
$ { echo aaaa; echo bbbb >/tmp/x; echo cccc; } >/tmp/y
$ cat x
bbbb
$ cat y
aaaa
cccc

even real nested redirection works
(not just with (), but even with {})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.