微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在bash中的另一个函数内定义一个函数

我有以下代码
func1(){
    #some function thing
    function2(){
        #second function thing
    }
}

我想调用function2但我得到一个错误function2:找不到

解决方案吗?

bash中的函数定义不工作,函数定义在许多其他语言中工作。在bash中,函数定义是一个可执行命令,用于定义函数效果(替换任何以前的定义),与变量赋值命令定义变量的值(替换任何以前的定义)非常相似。也许这个例子会澄清我的意思:
$ 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

现在,如果你还不知道这一点,我很确定这不是你嵌套函数定义的原因。这引出了一个问题:为什么你嵌套函数定义?无论你期望嵌套定义有什么效果,这不是他们在bash中做的;所以1)不要他们和2)找到一些其他的方式来完成任何你正在尝试得到的嵌套为你做。

原文地址:https://www.jb51.cc/bash/389397.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐