0

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

Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82

1 Answers1

3

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
choroba
  • 231,213
  • 25
  • 204
  • 289