Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash array of functions

I'm trying to create an array of functions in order to iterate through each function in order.

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

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

This just prints out FUNCTION.A and says command not found. I need it to run the function. Suggestions?

like image 263
Atomiklan Avatar asked Dec 03 '13 20:12

Atomiklan


2 Answers

Works fine for me.

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

OUTPUT:

Inside of FUNCTION.A
FUNCTION.B: command not found
FUNCTION.C: command not found
like image 196
PSkocik Avatar answered Sep 20 '22 05:09

PSkocik


Another way that I think looks a lot better

funcs_to_test=( voltage_force_landing voltage_warn_critical )

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

And make sure to have written your functions above where you call this code

like image 29
rasen58 Avatar answered Sep 19 '22 05:09

rasen58