I have the following code
func1(){ #some function thing function2(){ #second function thing } }
and I want to call function2
but I get an error function2 : not found
Is there a solution?
A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.
Defining a function doesn't execute it. To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.
Yes, it's possible. It is even possible to nest a function within another function, although this is not very useful.
In the myScript.sh file, we've defined a variable VAR and two functions: log_info() and log_error(). We can call the functions within the script file.
Limit the scope of the inner function
Use function defined with parenthesis ()
instead of braces {}
:
f() ( g() { echo G } g ) # Ouputs `G` f # Command not found. g
Parenthesis functions are run in sub-shells, which have the same semantics of ()
vs {}
, see also: Defining bash function body using parenthesis instead of braces
This cannot be used if you want to:
exit
cd
as those are lost in the created sub-shell.
See also: bash functions: enclosing the body in braces vs. parentheses
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