If I declare a function inside another function, it overwrites any previously declared function with the same name. This is NOT what I want.
Example:
#!/bin/bash
_test() { echo test; }
_myf() {
# I'm using the same name as the other function.
_test() { echo local test; }
# I'm expecting this call to print "local test"
_test
}
# I'm expecting this call to print "test"
_test
# I'm calling myf hopping it will print "local test" but leave function "_test" unchanged.
_myf
# I'm expecting this call to still print "test" but function _test has been irredeemably changed.
_test
What I hop to get is:
test
local test
test
What I get is:
test
local test
local test
How can I make sure that any function I declare inside a function stays local to the later function?
Bash has local variables, but not local functions.
As a work-around you can try a classic sub-shell (where a modern implementation might avoid the overhead of an extra process).
_myf() {
# I'm using the same name as the other function.
( # subshell start
_test() { echo local test; }
# I'm expecting this call to print "local test"
_test
) # subshell end
}
The last example on page Functions suggests that bash cannot do this.
The shell ksh has a namespace facility. So if you wrote your code as in file user6:
#!/bin/ksh
#!/bin/bash
_test() { echo test; }
_myf() {
# I'm using the same name as the other function.
namespace mine {
_test() { echo local test; }
# I'm expecting this call to print "local test"
_test
}
}
# I'm expecting this call to print "test"
_test
# I'm calling myf hopping it will print "local test" but leave function "_test" unchanged.
_myf
# I'm expecting this call to still print "test" but function _test has been irredeemably changed.
_test
exit $?
Does not work with the ksh on Solaris.
Solaris 11 ksh "Version JM 93u 2011-02-08" takes the namespace mine { } , but the _test inside it runs the global function.
However the .mine._test works.
And the namespace feature is not mentioned in the ksh man page.
--
Regarding the uniqueness of function names:
I would prefix the new function with the current function's name: _myf__test { }
Why do you want to have a local function? From my personal experience, the main use is for passing around (anonymous) function objects or closures, which can't be done in bash anyway. Where is the problem to just name it differently?