0

Trying to simplely reference an array

declare -a arr1
declare -a arr2
declare -a arr3

currentArr=arr1
currentArr+=('abc')

currentArr=arr2
currentArr+=('qrs')

currentArr=arr1
currentArr+=('def')

When I run something like this

printf '%s\n' "${arr1[@]}" # should print abc def

I get an unbound variable error.

How do I create a pointer to an array so that I can just swap what array that pointer points at?

I did some searching but the answers I've found seem to be copying the array to another variable.

Bash I'm using: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)

Options I have available: declare: usage: declare [-afFirtx] [-p] [name[=value] ...]

Can someone please explain why this is marked a duplicate of Indirect reference to array values in bash

I don't see how that answers my question. I'm trying to modify the original arrays through the indirection.

The examples in that answer

currentArr="${arr1}[@]"
currentArr+=('abc')

Does not work.

I would like to append new values to the original array through a reference.

Jerinaw
  • 5,260
  • 7
  • 41
  • 54
  • Where do you assign content to `arr1`? – Cyrus Oct 22 '19 at 18:09
  • I thought that this would do it currentArr+=('abc') – Jerinaw Oct 22 '19 at 18:10
  • 2
    `declare -n refname=destname` if you want a reference (a "namevar"). – Charles Duffy Oct 22 '19 at 18:13
  • ...so, this is duplicative of https://stackoverflow.com/questions/40307250/indirect-reference-to-array-values-in-bash, but the existing answers predate namevars being a released feature, so I'll want to add a more current one. :) – Charles Duffy Oct 22 '19 at 18:14
  • @CharlesDuffy I saw that one, and like I said it seemed to look like it was copying the array. – Jerinaw Oct 22 '19 at 18:16
  • (Oh, something I should have mentioned -- `unset -n refname` to clear the reference). – Charles Duffy Oct 22 '19 at 18:19
  • Apparently my bash does not support the -n flag. @CharlesDuffy declare: usage: declare [-afFirtx] [-p] [name[=value] ...] GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18) – Jerinaw Oct 22 '19 at 18:24
  • 1
    You are better off not using `/bin/bash` on macOS if you are specifically interested in `bash`, rather than POSIX, shell programming; it is *years* out of date. Either install a newer version yourself, or consider learning `zsh` (which *is* kept roughly up-to-date by macOS, especially now that it is the default login shell). I would not be surprised if macOS stops shipping *any* version of `bash` in the next year or two. – chepner Oct 22 '19 at 19:03

0 Answers0