Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Bash函数数组_Arrays_Bash_Function - Fatal编程技术网

Arrays Bash函数数组

Arrays Bash函数数组,arrays,bash,function,Arrays,Bash,Function,我试图创建一个函数数组,以便按顺序遍历每个函数 declare -a FUNCTION FUNCTION[1]="FUNCTION.A" FUNCTION[2]="FUNCTION.B" FUNCTION[3]="FUNCTION.C" for i in "${!FUNCTION[@]}"; do ${FUNCTION[$i]}; done 这只是打印出FUNCTION.A,并表示找不到命令。我需要它来运行函数。建议?对我来说很好 declare -a FUNCTION FUNCTION

我试图创建一个函数数组,以便按顺序遍历每个函数

declare -a FUNCTION
FUNCTION[1]="FUNCTION.A"
FUNCTION[2]="FUNCTION.B"
FUNCTION[3]="FUNCTION.C"

for i in "${!FUNCTION[@]}"; do
  ${FUNCTION[$i]};
done
这只是打印出FUNCTION.A,并表示找不到命令。我需要它来运行函数。建议?

对我来说很好

declare -a FUNCTION
FUNCTION[1]="FUNCTION.A"
FUNCTION[2]="FUNCTION.B"
FUNCTION[3]="FUNCTION.C"

#Define one of the functions
FUNCTION.A() { echo "Inside of FUNCTION.A"; }


$ for i in "${!FUNCTION[@]}"; do   ${FUNCTION[$i]}; done
输出:

Inside of FUNCTION.A
FUNCTION.B: command not found
FUNCTION.C: command not found

我是个白痴。。。。。。。。显然,函数必须位于调用它的位置之上。有点烦人。我希望所有函数都能位于底部。

可以从保存在数组中的名称定义函数,然后在定义后调用这些函数:

#!/bin/sh

declare -a functions=( a b c )
for f in ${functions[@]}; do
    eval "$f() { 
              echo "Hello from $f" 
              # ...
          }"
    $f
done
或者:

#!/bin/sh

declare -a functions=( a b c )

a() { echo "Hello from $FUNCNAME"; }
b() { echo "Hello from $FUNCNAME"; }
c() { echo "Hello from $FUNCNAME"; }

for f in ${functions[@]}; do 
    $f
done 

为了避免这个小麻烦,只需将脚本主体放入另一个函数中。(我通常称之为“app_main”,因为就bash而言,“main”是脚本函数的名称。)


另一种我认为看起来更好的方式

funcs_to_test=( voltage_force_landing voltage_warn_critical )

for testP in "${funcs_to_test[@]}"
do  
    $testP
done

并确保已在上面的调用代码处编写了函数

您也可以这样声明函数

FUNCTION=(FUNCTION.A FUNCTION.B FUNCTION.C)
然后像这样迭代:

for i in "${!FUNCTION[@]}"; do
${FUNCTION[i]}

这应该行得通。如果您只调用“$i”,它将只打印数组中的函数名。

这是因为您没有定义函数function.A本身。:)不幸的是,这并不总是调用相应的函数,它只打印函数名。要调用函数,应该将${funcs_写入_test[testP]}而不是$testP。
for i in "${!FUNCTION[@]}"; do
${FUNCTION[i]}