如何在Bash中的另一个函数中定义一个函数? [英] How to define a function inside another function in Bash?
本文介绍了如何在Bash中的另一个函数中定义一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
func1(){
#some function thing
function2(){
#second function thing
}
}
,我想打电话给function2
,但出现错误function2 : not found
and I want to call function2
but I get an error function2 : not found
有解决方案吗?
推荐答案
限制内部函数的作用域
使用带括号()
定义的函数代替括号{}
:
Use function defined with parenthesis ()
instead of braces {}
:
f() (
g() {
echo G
}
g
)
# Ouputs `G`
f
# Command not found.
g
肢体功能在子shell中运行,它们具有与()
和{}
相同的语义,另请参见:
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
- set variables
exit
cd
那些丢失在创建的子外壳中.
as those are lost in the created sub-shell.
另请参阅: bash函数:将身体括在括号中与括号
这篇关于如何在Bash中的另一个函数中定义一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文