cómo llamar funciones desde el bucle for en el script de shell

cómo llamar funciones desde el bucle for en el script de shell
array_item= (item1 item2)
#function
check_item1 ()
{
 echo "hello from item1"
}
check_item2 ()
{
echo "Hello from item2"
}
#calling functions
for (( i=0; i<${array_item[@]}; i++ ))
{
 check_${array_item[$i]}  # (expecting check_item1 then check_item2 funtion will be called)
}

Recibo el error check_: comando no encontrado cuando intento llamar a las funciones check_item1 y check_item2.

Respuesta1

array_item= (item1 item2)

No pongas espacios alrededor de la =tarea in, no funciona. Además esto me da un error de sintaxis sobre el paréntesis. Podría recibir el check_: command not founderror si los elementos de la matriz no están configurados o están vacíos.

for (( i=0; i<${array_item[@]}; i++ ))

${array_item[@]}se expande a todos los elementos de la matriz, creo que lo desea ${#array_item[@]}para la cantidad de elementos. Si la matriz está vacía, esto también debería dar un error, ya que faltará el otro operando de la comparación.

La for (( ... )) { cmds...}construcción parece funcionar en Bash, pero el manual solo describe la for (( ... )) ; do ... ; doneconstrucción habitual.

O simplemente utilícelo for x in "${array_item[@]}" ; do ... donepara recorrer los valores de la matriz.

Si necesita los índices mientras realiza el bucle, podría ser técnicamente mejor realizar el bucle "${!array_item[@]}", ya que en realidad no es necesario que los índices sean contiguos. Eso también funciona con matrices asociativas.

Respuesta2

Simplemente cambia tu bucle for:

for index in ${array_item[*]}
    do
       check_$index
    done

guión completo

#!/bin/bash

array_item=(item1 item2)

#function
check_item1 ()
{
   echo "hello from item1"
}
check_item2 ()
{
   echo "Hello from item2"
}   

for index in ${array_item[*]}
    do
       check_$index
    done

NB: Además, están disponibles las siguientes construcciones originales:

${array_item[*]}         # All of the items in the array
${!array_item[*]}        # All of the indexes in the array
${#array_item[*]}        # Number of items in the array
${#array_item[0]}        # Length of item zero

información relacionada