tiranodev
tiranodev

Reputation: 1003

How to define a function inside another function in 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?

Upvotes: 80

Views: 62519

Answers (8)

Jon Green
Jon Green

Reputation: 510

You can nest functions and make them locally-bound (without using a subshell) in this way:

fna() {
    local fnb
    fnb() {
        # ...do something...
    }
    fnb
}

The fnb() function is only visible within fna() but its actions take effect within fna()'s shell.

The main gotcha is that if you do a return from within fnb(), this only returns from fnb() of course: you'd have to check its return value ($?) within fna() and return from there if needed.

Upvotes: 1

Dark Angel
Dark Angel

Reputation: 105

finf.sh:

#!/bin/bash

func1()
{
  in1()
  {
    local r=$1$2
    echo "func1.in1: $r"
  }
  in2()
  {
    local r=$2$1
    echo "func1.in2: $r"
  }
  $@
}

func2()
{
  in1()
  {
    [ ${#1} -gt ${#2} ] && local r=$2 || local r=$1
    echo "func2.in1: $r"
  }
  in2()
  {
    [ ${#1} -eq ${#2} ] && local r=true || local r=false
    echo "func2.in2: $r"
  }
  $@
}

$@

exit 0
user@host:~/tmp$ ./finf.sh func1 in1 qwerty asdf
func1.in1: qwertyasdf
user@host:~/tmp$ ./finf.sh func1 in2 qwerty asdf
func1.in2: asdfqwerty
user@host:~/tmp$ ./finf.sh func2 in1 qwerty asdf
func2.in1: asdf
user@host:~/tmp$ ./finf.sh func2 in2 qwerty asdf
func2.in2: false

So you can call inner function by arg

Upvotes: 4

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

TODO: without subshell

Bash has local variables feature which allows allow you to not have to create a subshell by using {} instead of () as in:

f() {
  local g=G
  echo $g
}

# Ouputs `G`
f
# Outputs empty line, `$g` is undefined.
echo $g

this can be:

  • faster
  • more convenient if you want to modify the parent shell in other aspects, e.g. with exit or modifying other globals

Unfortunately, there don't seem to be an analogue for functions: Achieve Local Function

Upvotes: 103

Gordon Davisson
Gordon Davisson

Reputation: 125708

Function definitions in bash don't work the way function definitions work in many other languages. In bash, a function definition is an executable command which defines the effect of a function (replacing any previous definition), in much the same way that a variable assignment command defines the value of a variable (replacing any previous definition). Perhaps this example will clarify what I mean:

$ outerfunc1() {
> innerfunc() { echo "Running inner function #1"; }
> echo "Running outer function #1"
> }
$ outerfunc2() {
> innerfunc() { echo "Running inner function #2"; }
> echo "Running outer function #2"
> }
$
$ # At this point, both outerfunc1 and outerfunc2 contain definitions of
$ # innerfunc, but since neither has been executed yet, the definitions
$ # haven't "happened".
$ innerfunc
-bash: innerfunc: command not found
$
$ outerfunc1
Running outer function #1
$ # Now that outerfunc1 has executed, it has defined innerfunc:
$ innerfunc
Running inner function #1
$
$ outerfunc2
Running outer function #2
$ # Running outerfunc2 has redefined innerfunc:
$ innerfunc
Running inner function #2

Now, if you didn't already know this, I'm pretty sure this wasn't your reason for nesting function definitions. Which brings up the question: why are you nesting function definitions at all? Whatever effect you expected nested definitions to have, that's not what they do in bash; so 1) unnest them and 2) find some other way to accomplish whatever you were trying to get the nesting to do for you.

Upvotes: 70

ivan_pozdeev
ivan_pozdeev

Reputation: 35998

Your code should work as written provided you only call the nested function after it's defined.

As said in another answer, a func(){<...>} statement is an executable statement that defines a name (in the global scope) associated with the function. Just like if you defined a variable.

So, you can use func2 anywhere in the code after the func2(){<...>} statement has run:

#func2 not defined
func1(){
    #not defined
    func2(){<...>}
    #defined
}
#not defined
func1
#defined
func3(){
    #only defined if func3 is called after `func2(){<...>}' has run
}

Upvotes: 0

Brian
Brian

Reputation: 101

If you're nesting a function, say function2 inside function1, it doesn't become available until function1 is called. Some people might consider this a feature, as you can do something like "unset function2" at the end of function1 and its scope is completely local to that function (can't be called from elsewhere). If you want to call the function elsewhere, there's probably no need to nest it anyway.

Upvotes: 4

Teudimundo
Teudimundo

Reputation: 2670

In the question case I suppose that you were trying to call function2 before it is defined, "some function thing" should have been after the function2 definition.

For the sake of discussion, I have a case where using such definitions can be of some use.

Suppose you want to provide a function that might be complex, its readability could be helped by splitting the code in smaller functions but you don't want that such functions are made accessible.

Running the following script (inner_vs_outer.sh)

#!/bin/bash
function outer1 {
    function inner1 {
       echo '*** Into inner function of outer1'
    }
    inner1;
    unset -f inner1
}

function outer2 {
    function inner2 {
       echo '*** Into inner function of outer2'
    }
    inner2;
    unset -f inner2
}
export PS1=':inner_vs_outer\$ '
export -f outer1 outer2

exec bash -i

when executed a new shell is created. Here outer1 and outer2 are valid commands, but inner is not, since it has been unset exiting from where you have outer1 and outer2 defined but inner is not and will not be because you unset it at the end of the function.

$ ./inner_vs_outer.sh
:inner_vs_outer$ outer1
*** Into inner function of outer1
:inner_vs_outer$ outer2
*** Into inner function of outer2
:inner_vs_outer$ inner1
bash: inner1: command not found
:inner_vs_outer$ inner2
bash: inner2: command not found

Note that if you define the inner functions at the outer level and you don't export them they will not be accessible from the new shell, but running the outer function will result in errors because they will try executing functions no longer accessible; instead, the nested functions are defined every time the outer function is called.

Upvotes: 24

Charlie Martin
Charlie Martin

Reputation: 112346

Don't nest function definitions. replace with:

$ cat try.bash 
function one {
  echo "One"
}

function two {
  echo "Two"
}

function three {
   one
   two
}

three
$ bash try.bash 
One
Two
$ 

Upvotes: 14

Related Questions