首页 > 解决方案 > 遍历函数名数组并在 bash 脚本中执行所有这些函数名

问题描述

我编写了一个 bash 脚本,我有一个函数名数组,其中传递了变量,我想在一个循环中执行所有这些。

但是当我执行 bash 脚本时,我得到了这个错误:

a: 找不到命令

我怎样才能做到这一点?

我的 bash 脚本如下所示:

#!/bin/bash

functions_array=("test a" "test b" "testc")

test() {
        echo $1
}

testc() { echo "testc!"; }

for i in ${functions_array[@]}; do
        ${i}
done

标签: linuxbashfor-loop

解决方案


你得到这个错误是因为你没有引用你的变量。因此test a分为两部分。

试试这样:

#!/bin/bash

functions_array=("test a" "test b" "testc")

test() {
        echo "$1"                          # quoting here and ...
}

testc() { echo "testc!"; }

for i in "${functions_array[@]}"; do       # also here
        ${i}
done

推荐阅读