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
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.
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.
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 ...'
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.
Hmm, when in doubt, use ( )
which will run a subshell and redirect its entire output.
So, try something like:
( mytoplevelfunc ) | tee whatever
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With