簡體   English   中英

Shell 腳本調用帶有變量的 function?

[英]Shell Script call a function with a variable?

嗨,我正在創建一個 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
#!/bin/bash
test_func() {
    echo "It works!"
}

function_name="test_func"

eval ${function_name}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM