Timeline for How to pass an array as function argument?
Current License: CC BY-SA 3.0
9 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Jun 3, 2022 at 18:06 | comment | added | ebsf | This is quite helpful. I wonder, though, about the statement in man bash-builtins (for the declare -n option, which local incorporates): "The -n attribute cannot be applied to array variables." I don't know enough yet to know what to make of this statement in light of this answer. Can someone comment? | |
Jun 10, 2021 at 14:00 | comment | added | Davos |
EDIT: I see what you mean; second part of what I said is incorrect. I tried changing the local arr to n as well and it does echo a warning about circular name reference - but it doesn't error, it still runs. x-yuri's suggestion deals with that warning nicely.
|
|
Jun 10, 2021 at 13:28 | comment | added | Davos |
@Sapphire_Brick why would an array named n be a circular reference? If you changed the name array to n and called the function e.g. copyFiles n then inside the function the local variable arr is created effectively as an alias or synonym of n . local -n arr also means a locally (function) scoped variable so even if you called that n as well it wouldn't be circular. The fact that changing the arr inside the function also changes the value of array outside the function is not circular either, it's because both names ultimately point to values in the same address space.
|
|
Jan 12, 2021 at 19:21 | review | Suggested edits | |||
Jan 13, 2021 at 6:44 | |||||
Jan 12, 2021 at 19:13 | comment | added | x-yuri |
Bash is not Haskell. You've got to compromise. On a different note, it makes sense to do [ "$1" = arr ] || local -n arr=$1 in place of just local -n arr=$1 . That way the argument and the parameter names can coincide. As far as I can tell, the scope in bash is dynamic.
|
|
Aug 19, 2020 at 11:11 | comment | added | Anthony Rutledge | @user448115 Yes, but what if the input array is not ever supposed to be changed by the function in question. In effect, what if the passing of an array is only being done to get a result. Exposing your inputs to potentially unexpected data mutations is not wise. | |
May 4, 2019 at 18:47 | comment | added | dtmland | Requires bash 4.3+ | |
Sep 15, 2015 at 12:27 | comment | added | Ahasanul Haque | Though, it wasn't exactly what i want, but it still nice to know how pass by reference work in bash. +1 :) | |
Sep 15, 2015 at 10:15 | history | answered | user448115 | CC BY-SA 3.0 |