bash - 如何在 Bash 中的另一个函数中定义一个函数?

标签 bash

我有以下代码

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/

相关文章:

c - 生成文件语法 : what is $(RM)?

ruby-on-rails - 如何在 Ruby 中处理包含空格的文件名(在 Git Bash 中)

c# - 执行脚本时将参数传递给 bash

bash - 在Ubuntu中,如何删除当前目录中某个用户的所有文件

mysql - 以非交互方式在命令行中执行 Google Cloud SQL 查询

linux - ASN 查找别名不起作用

node.js - Node 在 Windows 上的 Ubuntu 上无法在 Bash 上运行

bash - 替换 txt 文件中每一行匹配文本的第一个实例

bash - 从终端/bash 获取 Macbook 屏幕尺寸

linux - 如何将文件名改为小写?