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

3
  • 1
    @anubhava added to the bottom of question Commented Nov 14, 2016 at 17:42
  • 1
    Related, maybe even a dupe: stackoverflow.com/questions/1063347/… Commented Nov 14, 2016 at 17:47
  • 1
    It is working now, I think what happened is I called the function with a parameter that didn't have the dollar sign in front of it one time like printarr arr Commented Nov 14, 2016 at 17:50

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.