2

How can I define a function as an element of an array?

I know I can do this:

function array[5](){ echo "you are inside the function"; }

And it is a valid function, in the sense that, the instruction array[5], correctly execute the function.

Unlucky, the function is not listed in the keys of the array, so, echo ${!array[*]} does not return 5 as a key.

For instance, the following code:

array[0]="first"
function array[5](){ echo "you are inside the function"; }
array[7]="seventh"
echo ${!array[*]}

Only returns 0 7.

So, how can I add a function to an array element, so that I can loop over it?

1 Answer 1

6

You can't really put the function itself in the array. But what you can do is put the function name in that field. Look:

a_pretty_function() {
    echo "you're inside a function";
}
array[5]=a_pretty_function

# Execute it:
"${array[5]}"

When you're doing

array[5]() { echo "you are inside the function"; }

you're defining a function called array[5] as you can check with declare -pf array[5].

With this mechanism you can do something horribly ugly:

array[5]() { echo "you are inside the function"; }
i=5
"array[$i]"

and this will execute the function array[5]. I wouldn't recommend such a practice in any case.

Sign up to request clarification or add additional context in comments.

2 Comments

Indeed the key is that last bit. Variables and functions don't share a namespace.
It also demonstrates that array[5] isn't so much an index operation as a name that bash treats specially for parameter expansion. Arrays are just ugly in bash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.