如何定义在bash另一个函数里面的函数 [英] How to define a function inside another function in bash

查看:97
本文介绍了如何定义在bash另一个函数里面的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code

func1(){
#some function thing
function2(){
#second function thing
}
}

和我要调用函数2,但我得到说函数2错误:未找到结果
有解决办法吗?

and i want to call function2 but i get an error that say function2 : not found
there is solution?

推荐答案

在bash函数定义不工作方式的函数定义在许多其他语言。在bash中,函数定义是一个的执行的命令,它定义了一个函数的效果(更换任何previous的定义),在大致相同的方式,一个变量赋值命令定义一个变量的值(更换任何previous定义)。也许这个例子会澄清我的意思是:

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

现在,如果你还不知道这一点,我是pretty肯定这是不是你的原因嵌套函数定义。这带来了一个问题:为什么的的嵌套你在函数的所有定义?不管效果,你预期嵌套定义有,这不是他们在bash做什么;所以1)UNNEST他们和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.

这篇关于如何定义在bash另一个函数里面的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆