简体   繁体   中英

Loop through array of function names and execute all of them in a bash script

I write a bash script and i have an array of function names with variable passed to them and i want to execute all of them in a loop.

but when i execute the bash script, i get this error:

a: command not found

how can i do this?

my bash script is look like this:

#!/bin/bash

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

test() {
        echo $1
}

testc() { echo "testc!"; }

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

You get this error because you didn't quote your variables. Therefore test a is split into two parts.

Try it like this:

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM