How to redirect the output of nested function calls in bash?

I have a bash script that has several functions that are all called within 1 function. How can I pass all the output from all functions to the main? I also use tee to display this output for the term and for the 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 
+4
source share
3 answers

Hmm, if in doubt, use ( ) , which will launch a subshell and redirect its entire result.

So try something like:

 ( mytoplevelfunc ) | tee whatever 
+7
source

As DigitalRoss said, all stdouts go to the same place, and working with pipelines and shields works regardless of how deeply the functions and scripts are embedded (up to system restrictions). In the demo below, f4 demonstrates one way to execute 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 
+3
source
 $ { echo aaaa; echo bbbb >/tmp/x; echo cccc; } >/tmp/y $ cat x bbbb $ cat y aaaa cccc 

even real nested redirects work
(not only with () , but even with {} )

0
source

All Articles