How to Pass Array as an Argument in Bash Function? [3 Ways]

To pass an array as an argument to a Bash function use the following techniques

1. Pass My_array as an argument of My_function using name reference:

My_function My_array

2. Pass My_array to My_function after expanding it using the array expansion technique:

My_function "${My_array[@]}"

3. Pass My_array after converting it into a string, say arrayString:

My_function "$arrayString"

3 Ways to Pass an Array to a Bash Function

In Bash scripting, arrays can be passed to functions in various ways. The basic technique includes creating a name reference of the array passed to the function. Moreover, one can pass an array to a function as a string and later convert the string to the actual array within the function. Furthermore, an array can be passed by expanding the array and parsing its elements as different arguments. This article will discuss all three approaches elaborately.

1. Using Name Reference

To pass an array to a Bash function, you can use the local keyword to create a name reference and assign it to a variable. This variable can then be used within the function to access and modify the array. Here is an example:

#!/bin/bash

# Define function to operate on array
function passarray {
    local -n arr=$1  # Create a nameref
    # Access array elements using ${arr[@]} syntax
    for element in "${arr[@]}"; do
        echo "$element"
    done
}

# Declare array (corrected syntax)
distros=("Ubuntu" "Fedora" "Debian" "Arch Linux")

# Call function and pass distros array as an argument
passarray distros
EXPLANATION

This Bash script defines a function named passarray that operates on an array passed as an argument. The function uses local -n to create a name reference for the array passed as the first argument, assigning it to the variable arr. Inside the function, a for loop iterates over each element of the arr, printing them one by one. Before calling the function, the script declares an array named distros, which holds four Linux distribution names. Finally, the function “passarray” is invoked with the distros array passed as an argument.

Pass array as an argument in Bash functionOnce executed the script prints the elements of the distros array. Therefore, It is evident that the “distros” array is properly passed to the “passarray” function.

Note: -n option of the local command in must here. Otherwise, it will fail to create a name reference of the array passed as an argument.

Note: If you carefully look at the argument passed to the function, you will find that the array name doesn’t use parameter expansion to refer to the array variable distros such as $distros. Rather it uses an indirect referencing technique to indicate that “distros” is not just a string but an array.

2. By Expanding an Array

To pass an array to a Bash function first expand the whole array. Then use parameter expansion to pass the array as an argument. For instance, “${myArray[@]}” can pass “myArray” to a function. Here, [@] is used to expand the array and parameter expansion ${ } facilitates to pass it as an argument. The following script includes such an example:

#!/bin/bash

# Function that receives an array argument
array_element() {
  cp_array=("$@")  # Assign the passed array to a local array variable
  # Print array elements
  echo "First element: ${cp_array[0]}"
}

# Declare an array
myArray=(5 3 9 Null)

# Call the function and pass an argument of an array
array_element "${myArray[@]}"
EXPLANATION

This Bash script defines a function named “array_element” which receives an array argument. Within the function, the elements of the passed array are copied to a local array variable cp_array. Then, the first element of the array is printed using "${cp_array[0]}". After declaring an array named myArray, the function “array_element” is called with "${myArray[@]}" to pass the entire array as arguments.

Pass array as an argument in Bash function using array expansion

After the array is passed to the function, it prints the first element of the array which is 5.

Note: Passing an array to a function using the array expansion technique splits the array elements into different positional arguments. Therefore, it may cause issues when you have some extra argument to pass along with the array argument.

To overcome the limitation of the array expansion technique one can use the shift command. For example, if you have an extra argument passed right before the array, then use shift 1 to remove the first argument from the command-line arguments passed to the function. This allows you to get the array within the function using “$@” again. See the demonstration below:

#!/bin/bash

# Function that receives an array argument
shift_element () {
  shift 1
  cp_array=("$@")  # Assign the passed array to a local array variable
  # Print array elements
  echo "Array elements: ${cp_array[@]}"
}
# Declare an array
myArray=(5 3 9 Null)

# Call the function and pass an argument of an array
shift_element "arg1" "${myArray[@]}"
EXPLANATION

The Bash script defines a function named “shift_element”. Within the function, it shifts the arguments to the left by one position using shift 1, then assigns the remaining arguments to a local array variable cp_array. It prints all the elements of the array using ${cp_array[@]}. Outside the function, an array named myArray is declared. Finally, the function “shift_element” is called with the argument “arg1” and the elements of myArray.

Escaping non-array argument using shift

The image shows that the program prints all elements of the array, escaping the non-array first argument using shift 1.

3. As an Array String

An array can be passed to a Bash function by converting the whole array into a string. Then the string is provided as an argument of the function. Utilize the read command to recover the array from the string. Here is an example:

#!/bin/bash
# Define function to operate on array
function array_str {
    # Convert string back to array
    read -a arr <<< "$1"
    # Access array elements using ${arr[@]} syntax
    for element in "${arr[@]}"; do
        echo "$element"
    done
}

# Declare array
myArray=(5 3 9 Null)

# Convert array to string
arrayString="${myArray[*]}"

# Call function and pass array as string
modifyArray "$arrayString"
EXPLANATION

This Bash script defines a function named “array_str”. Within the function, it converts the string of the first positional argument back into an array using redirection with the read command (read -a arr <<< "$1"). Subsequently, it iterates over the elements of the array arr using a for loop and prints each element.

Before calling the function, the script declares an array named myArray. To pass the array to the function, the script converts it to a string using "${myArray[*]}" and stores it in the variable arrayString. Finally, the “array_str” function is called with the arrayString variable passed as the first argument.

Pass array as an argument after converting it into a string

As expected the program can convert the array string back to the array. After reading the elements of the array, it prints them as shown in the image above.

Note: Keep in mind that this approach involves converting the array into a string and then back into an array, which may not be the most efficient solution in all cases.

3 Practical Examples of Passing an Array to a Bash Function

There are numerous real-world cases where users need to pass an array to a Bash function. Sometimes, the required array to pass may be empty. In other cases, there may be additional arguments to pass. These scenarios may vary depending on the situation. Now, this article will dive into three such cases where passing an array as an argument to a function is crucial.

1. Pass an Empty Array as an Argument in Bash Function

Sometimes users may not know the size of the array passed to a function, leading to accidental passing of an empty array. Setting a default value when passing the array to the function helps ensure that the function can still process it even if it’s empty. For example, passing an array named Myarray as ${Myarray[@]:-“”} will expand to an empty string if “Myarray” doesn’t contain any elements. Here is an example:

#!/bin/bash
function passempty () {
    if [ $# -le 1 ]; then
        return 1
    fi
    echo "Empty array passed."
    return 0
 }
Myarray=()
passempty "" "${Myarray[@]:-""}"
EXPLANATION

This Bash script defines a function named “passempty” which can handle an empty array. If the number of arguments is less than or equal to 1, it returns an exit status of 1, indicating an error. Otherwise, it prints “Empty array passed.” and returns an exit status of 0. An empty array named Myarray is declared. Finally, the “passempty” function is called with two arguments: an empty string "" and "${Myarray[@]:-""}", which evaluates to an empty string if Myarray is unset or null.

Passing an empty array to a Bash function

As “Myarray” takes its default value, two empty strings are passed to the function. Therefore, the script doesn’t show any error and prints the message that “Empty array passed.”

2. Pass and Update Arrays in Bash Function

To update arrays in a Bash function so that the changes persist outside of the function, pass the array using a nameref. Here’s how you can do it:

#!/bin/bash

modifyArray() {
    local -n arr=$1
    arr[3]=12
}

# Declare an array
Myarray=(5 3 9 Null)

echo "Before modification:"
echo "${Myarray[@]}"

# Call the function and pass the array
modifyArray Myarray

echo "After modification:"
echo "${Myarray[@]}"
EXPLANATION

This Bash script defines a function called “modifyArray”, which takes an array as its argument. Within the function, it creates a local copy of the array argument passed to the function using local -n arr=$1 command. After that, a new value is assigned at index 3 of the array.

The script then declares an array named Myarray with initial values and displays its contents before calling the “modifyArray” function. Upon invocation, the function alters the value of the fourth element of the Myarray to 12. Finally, the program displays the modified array.

Modify array after passing it to a Bash functionThe image shows that the fourth element was “Null” before passing the array to the function. However, after modifying the array within the function the change persists outside of the function and the fourth element becomes 12.

3. Passing Non-Array Argument with Array to a Function

When a function requires multiple arguments, including both an array and regular arguments, passing the array alongside additional arguments can be challenging. Passing the array using name reference is advantageous in this situation. The following script demonstrates this:

#!/bin/bash
extra_arg() {
    local -n arr=$1
    echo "Array passed to the function: ${arr[@]}"
    echo "Additional argument passed to the array: $2"
}

Myarray=(5 3 9 Null)
extra_arg Myarray 20
EXPLANATION

This Bash script defines a function named “extra_arg” that takes an array and an additional argument. Inside the function, it creates a nameref variable arr using local -n arr=$1 command to reference the array passed to it. It then prints out the array. Moreover, it also displays the additional argument using the second positional parameter ($2).

Next, the script initializes an array called Myarray and calls the “extra_arg” function with myArray and 20 as arguments.

 Passing non-array argument with array argument to a Bash function

The function displays the content of the array (Myarray) passed to it and the additional argument (20).

Conclusion

In conclusion, passing arrays to functions in Bash requires careful consideration. Utilizing name reference (local -n) provides direct access to the original array, facilitating modifications within the function. This is particularly useful for handling array and non-array arguments altogether. Additionally, array expansion can be used to pass an array to a function. However, it’s crucial to be cautious about whether the array is empty. I believe this discussion has helped you to understand various ways to pass an array to a Bash function.

People Also Ask

What is the best way to pass an array to function?

The best way to pass an array to a function in Bash is by using namerefs (local -n). For instance, if you have an array called Myarray and a function called Myfunction, pass the array to function by Myfunction Myarray. Within the function get the array using local -n Myarray=$1. Moreover, one can also utilize indirect referencing. This approach allows for modifying the actual array within the function.

What will happen when passing the array like a variable?

When passing an array like a variable in Bash, only the first element of the array will be passed to the function. For instance, if Myarray is passed as $Myarray, only the first element of “Myarray” will be passed to the function. To ensure that all elements of the array are passed, you should use the appropriate syntax, such as "${Myarray[@]}", to pass the entire array. However, it’s important to note that when you use “${Myarray[@]}”, elements of the array are passed as different arguments, not as a single argument, which can cause issues while passing multiple arguments.

How to set a default value of an array when passed to a function?

To set a default value for an array passed to a Bash function, you can use parameter expansion. For instance, consider the syntax: Myfunction "${Myarray[@]:-""}". This ensures that if Myarray is empty or unset, it will default to an empty string.

What is an array in Bash?

An array in Bash is a collection of elements. It is a structured way to organize and access data. In Bash, an array is always enclosed by the first bracket. There are two types of arrays. Index array and associate array. An index array looks like the following:

My_array=("a" "b" "c")

Here, My_array is an array of three elements. The index of the elements starts from zero. Hence, the index of element “a” is 0, the index of “b” is 1 and so on.

Unlike an indexed array, an associate array is a collection of data with a key associated with each element of the array. Look at the example of the following associative array:

declare -A My_array ( [User]=Anita [ID]=20134 [Shell]=sh )

Here, My_array is an associate array of three key-value pairs. The value of the [User] key is “Anita”.

Related Articles


<< Go Back to Argument in Bash Script | Bash Functions | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment