Kolob Canyon Kolob Canyon - 26 days ago 7
Linux Question

Bash function to print array on multiple lines

I wrote this function to print arrays in bash without using that horrible bracket syntax:

printarr()
{
arr=$1 # first argument
printf '%s\n' "${arr[@]}"
}


Does not work as expected.

It will print out the first array you feed it, but then if you feed it another array it will print out the first one again.

I call it like this

$ arr=( "single" "line" "arr" )
$ printarr $arr
$ multiarr=( "multi"
> "line"
> "arr")
$ printarr $multiarr


GNU bash, version 3.2.25(1)-release

Answer

If you don't want to use brackets when sending the array to the function, send just its name and use indirect expansion:

#! /bin/bash
printarr()
{
     arr=$1'[@]'
     printf '%s\n' "${!arr}"
}

arr1=( "single" "line" "arr with spaces" )
arr2=( "SINGLE" "LINE" "ARR WITH SPACES" )

printarr arr1
printarr arr2