Using bash 4.3, declare -n aliasName=destVarName
will make aliasName
refer to destVarName
, even for arrays; thus permitting any kinds of assignment, dereferencing, &c. you would otherwise use.
#!/usr/bin/env bash
# ^^^^^^^^ - Use bash version from PATH; on MacOS, this should be newer
# than the system one if MacPorts, Homebrew, etc. is installed.
case $BASH_VERSION in
''|[1-3]*|4.[0-2]*) echo "This code requires bash 4.3 or newer" >&2; exit 1;;
esac
# to make "index0", "index1", &c. valid indexes, our arrays need to be associative
declare -A arrayFolder1 arrayFolder2
var1=1
declare -n curArrayFolder=arrayFolder$var1
curArrayFolder[index0]=file1
curArrayFolder[index1]=file2
curArrayFolder[index2]=file3
unset -n curArrayFolder
var1=2
declare -n curArrayFolder=arrayFolder$var1
curArrayFolder[index0]=file4
curArrayFolder[index1]=file5
curArrayFolder[index2]=file6
unset -n curArrayFolder
...will properly result in a situation where:
declare -p arrayFolder1 arrayFolder2
emits as output:
declare -A arrayFolder1=([index0]="file1" [index1]="file2" [index2]="file3" )
declare -A arrayFolder2=([index0]="file4" [index1]="file5" [index2]="file6" )
If you want to try to cut down the number of commands needed to switch over which folder is current, consider a function:
setCurArrayFolder() {
declare -p curArrayFolder &>/dev/null && unset -n curArray
declare -g -n curArrayFolder="arrayFolder$1"
var1=$1
}
Then the code becomes:
setCurArrayFolder 1
curArrayFolder[index0]=file1
curArrayFolder[index1]=file2
curArrayFolder[index2]=file3
setCurArrayFolder 2
curArrayFolder[index0]=file4
curArrayFolder[index1]=file5
curArrayFolder[index2]=file6