4

Specs

GNU bash, version 3.1.17 (No possibility of upgrade)


Premise

I've been messing around with arrays and i was wondering if there is any way to have a variable local to a function with the same name as an array outside of said function.


Example

In the below examples I will try to display the issue

Working

#!/bin/bash
arr=(1 2 "3 4" 5)   # Make global array

myfunc()
{
    local args=("${!1}")  # Using different name for declaration
        echo ${args[@]}  # Echo new array


}
    myfunc arr[@]  # Pass array to function

Output

1 2 3 4 5

Not working

#!/bin/bash

arr=(1 2 "3 4" 5) # Create array

myfunc()
{
    local arr=("${!1}") #Not working
        echo ${arr[@]} # Not working


}
    myfunc arr[@] # Pass array to function

Output

[Blank]

Reason

I want to pass multiple arrays to the function but do not want to have a possible name collision with the array being passed in and the local array name.


Tried

As you can see above i have tried adding the local function. I've scanned the bash man page and cannot seem to find anything else that could provide the behaviour i desisre

Bash -x Results

+ arr=(1 2 "3 4" 5)
+ myfunc 'arr[@]'
+ arr=("${!1}")
+ local arr
+ echo

If any more information is needed then please let me know.

8
  • 1
    Your second snippet works just fine. See ideone.com/9Jjb3b . Your lack of quotes around ${arr[@]} in the function mean you are blowing up your spaces but that's a different issue. Jul 30, 2015 at 15:17
  • What is your bash version?
    – rici
    Jul 30, 2015 at 19:04
  • @EtanReisner I didn't really mind the spaces blowing up, but it honestly doesn't work. I don't know if the version of bash would have anything to do with it(I doubt it though).
    – 123
    Jul 31, 2015 at 7:16
  • @rici GNU bash, version 3.1.17, sorry for the late reply.
    – 123
    Jul 31, 2015 at 7:16
  • @EtanReisner Okay so i tried it GNU bash, version 3.2.51 and it works, any idea why it wouldn't on 3.1.17 ?
    – 123
    Jul 31, 2015 at 13:46

1 Answer 1

2

Congratulations you've hit a bug in the 3.1 series of bash.

From the Bash ChangeLog in the section relating to the bash-3.2-alpha release:

This document details the changes between this version, bash-3.2-alpha, and the previous version, bash-3.1-release.

...

f. Fixed two bugs with local array variable creation when shadowing a variable of the same name from a previous context.

1
  • Thankyou for this answer, really appreciate you looking around for this! And now i know where to look in the future if i get stuck again :)
    – 123
    Jul 31, 2015 at 17:31

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.