How to Pass Arrays as Parameters in Bash

Let’s say we have a function in bash which simply iterates through all elements from array and prints them on the standard output.

We can call this function in the following way

If we want to call function with other parameters we need to update arr variable accordingly

So far so good. But what if we want to make our printElems function generic and put it to the separate file. Is it wise enough to stay with our solution to maintain arr variable in global scope ? The answer is - it depends on the size of the project. It is obvious that maintaining global variables is cumbersome in projects which are getting bigger and bigger during their lifetime. So that is there any smart way to improve our function to not pollute the global scope ?

The answer is yes, and in this task will help us bash feature called ‘indirect variable reference’.

Below is an improved version of printElem function. A new function (printElems2) is not dealing with global variable at all. In fact the function receives a variable name and thx to the indirect reference operator \$(!variable_name) the value of the function parameter is set to local variable called my_arr.