DEV Community

Cover image for Returning an Array from a Bash Function
John Robertson
John Robertson

Posted on

Returning an Array from a Bash Function

At first glance it may seem that returning an array from a Bash function is not possible. This is not strictly true; taking a cue from the way C/C++ programmers might do this, you can pass the result array to the function by reference. This approach allows the function itself to remain free of any global variable references. Here is a simple example:

#!/bin/bash

# Example of how to return an array from a function
# using pass-by-reference.

# Halt on error, no globbing, no undeclared vars
set -efu

function getFnames
####################################################
# Load all filenames into an array. 
# Arguments:
#    $1 = name of return array (must be global)
#    $2 = first path for 'find' command to search
#    ...  other paths for 'find' to search
#
{
   # store the name of the global array for return.
   local h_rtnArr=$1
   # discard first argument in argv
   shift

   # mapfile does heavy lifting.  See: help mapfile
   mapfile $h_rtnArr < <(find $@ -type f)

   # TODO: return error code
}

# Global array
declare -a FnameArr

# Pass FnameArr by reference
getFnames FnameArr /boot

# List results to stdout
arrSz=${#FnameArr[@]}
for (( ndx=0; ndx < $arrSz; ++ndx )); do
   echo -n "${ndx}: ${FnameArr[$ndx]}"
done

Running this script will produce an enumerated list of all files on your /boot partition.
Enjoy!

Latest comments (2)

Collapse
 
vlasales profile image
Vlastimil Pospichal

Array in Bash? Why?

Collapse
 
jrbrtsn profile image
John Robertson

Same reason as any language I suppose. I have found uses for them from time to time, particularly associative arrays.