我有以下代码
func1(){
#some function thing
function2(){
#second function thing
}
}
我想调用 function2
但出现错误 function2 : not found
有解决办法吗?
最佳答案
限制内部函数的范围
使用用括号 ()
代替大括号 {}
定义的函数:
f() (
g() {
echo G
}
g
)
# Ouputs `G`
f
# Command not found.
g
括号函数在子 shell 中运行,具有与 ()
和 {}
相同的语义,另请参见:Defining bash function body using parenthesis instead of braces
如果你想这样就不能使用:
- 设置变量
退出
cd
因为它们在创建的子 shell 中丢失了。
另请参阅:bash functions: enclosing the body in braces vs. parentheses
TODO:没有子 shell
Bash 具有局部变量功能,允许您不必使用 {}
而不是 ()
创建子 shell,如:
f() {
local g=G
echo $g
}
# Ouputs `G`
f
# Outputs empty line, `$g` is undefined.
echo $g
这可以是:
- 更快
- 如果你想在其他方面修改父 shell 更方便,例如使用
exit
或修改其他全局变量
不幸的是,似乎没有函数的类似物:Achieve Local Function
关于bash - 如何在 Bash 中的另一个函数中定义一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8426077/