【问题标题】:Shell Script call a function with a variable?Shell 脚本调用带有变量的函数?
【发布时间】:2011-09-30 06:46:12
【问题描述】:

您好,我正在创建一个 shell 脚本。

示例代码如下所示

#!/bin/bash

test_func(){
{
  echo "It works!"
}

funcion_name = "test_func"

我希望能够以某种方式使用变量“function_name”调用 test_func()

我知道在 php 中使用 call_user_func($function_name) 或通过 sying $function_name() 是可能的

这在 shell 脚本中也可以吗?

非常感谢您的帮助! :)

【问题讨论】:

    标签: function shell variables call


    【解决方案1】:

    您想要 bash 内置 eval。来自man bash

    eval [arg ...] The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0.

    您也可以通过简单的变量替换来完成它,如

    #!/bin/bash
    
    test_func() {
      echo "It works!"
    }
    
    function_name="test_func"
    
    $function_name
    

    【讨论】:

    • 尝试您的提示之一,它尝试将 test_func 作为 shell 命令执行,而不是调用函数:(
    • @Ben - 不确定你的意思 - 两种方式都适合我。当你定义一个函数时,它本质上就变成了一个 shell 命令。如果你给出一个更具体的例子来说明什么不起作用,它可能会有所帮助。
    • 非常javascvript-esque
    【解决方案2】:
    #!/bin/bash
    test_func() {
        echo "It works!"
    }
    
    function_name="test_func"
    
    eval ${function_name}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多