Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a function inside another function in Bash?

Tags:

bash

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?

like image 337
tiranodev Avatar asked Dec 08 '11 04:12

tiranodev


People also ask

Can you define function inside another function?

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.

How do you call a function within a function in bash?

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.

Can you nest functions in bash?

Yes, it's possible. It is even possible to nest a function within another function, although this is not very useful.

Can we call function inside function in shell script?

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.


1 Answers

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:

  • set variables
  • exit
  • cd

as those are lost in the created sub-shell.

See also: bash functions: enclosing the body in braces vs. parentheses