function - Shell脚本调用带有变量的函数?

标签 function shell variables call

嗨,我正在创建一个 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脚本中也可能吗?

非常感谢您的帮助! :)

最佳答案

您想要内置的 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

关于function - Shell脚本调用带有变量的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6607993/

相关文章:

shell - 'date --date' 的 AIX 等效项

arrays - 如何将数组传递给 bash 函数

regex - sed 命令在 block /段落后插入行并在文件中进行更改

javascript - 显式赋值后 JavaScript 中的变量未定义?

variables - 无法访问函数内部的全局变量

javascript - 函数循环问题

php - "undefined function exif_read_data()"错误仅通过 Cron

javascript - 独立的事件处理程序以实现可重用性

Mysql函数用描述替换多个id

variables - SSIS 根据另一个变量的关闭日期将变量设置为下周一