DEV Community

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

Posted on

1 1

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!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top 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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more