Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect output of nested function calls in bash?

Tags:

bash

pipe

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
like image 733
zarzar Avatar asked Sep 22 '10 13:09

zarzar


People also ask

How to return something from a function in bash?

A bash function can return a value via its exit status after execution. By default, a function returns the exit code from the last executed command inside the function. It will stop the function execution once it is called. You can use the return builtin command to return an arbitrary number instead.

How do I redirect a output to a file in bash?

For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.

How do you redirect the output of a command to a variable in a shell script?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'

How to end a function bash?

The “exit 0” clause has been used here. After executing the “echo” statement, the bash script will be quitted, and no more execution will be performed due to “exit 0”. Otherwise, if the condition doesn't satisfy, the “echo” statement outside of the “if” statement will be executed.


2 Answers

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

So, try something like:

( mytoplevelfunc ) | tee whatever
like image 122
DigitalRoss Avatar answered Oct 23 '22 08:10

DigitalRoss


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
like image 40
Dennis Williamson Avatar answered Oct 23 '22 08:10

Dennis Williamson