Kolob Canyon Kolob Canyon - 1 year ago 110
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:

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 Source

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
     printf '%s\n' "${!arr}"

arr1=( "single" "line" "arr with spaces" )

printarr arr1
printarr arr2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download