1
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)
}

I'm getting error check_: command not found when tring to call check_item1 & check_item2 functions.

2 Answers 2

5
array_item= (item1 item2)

Don't put spaces around the = in assignment, it doesn't work. Also this gives me a syntax error about the parenthesis. You could get the check_: command not found error if the array elements are unset or empty.

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

${array_item[@]} expands to all elements of the array, I think you want ${#array_item[@]} for the number of elements. If the array is empty, this should also give an error, since the other operand to the comparison will be missing.

The for (( ... )) { cmds...} construct seems to work in Bash, but the manual only describes the usual for (( ... )) ; do ... ; done construct.

Or just use for x in "${array_item[@]}" ; do ... done to loop over the values of the array.

If you do need the indices while looping, it might be technically better to loop over "${!array_item[@]}", since the indices don't actually need to be contiguous. That works with associative arrays too.

2

Just change your for loop :

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

Full script

#!/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: In addition the following funky constructs are available:

${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
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .