2

I have three arrays:

array1=(8 7 6 5 4 3 2 1)
declare -a array2
declare -a array3

And X that representing which array I should use for some operation So, first of all I am finding it like this:

nameOfArray=array$X[@]
indirectTempArray=("${!nameOfArray}")
echo ${indirectTempArray[@]}  // returns 8 7 6 5 4 3 2 1 in case if X == 1

So, the question is, how I can delete value from original array which reference I have?

Cyrus
  • 84,225
  • 14
  • 89
  • 153

2 Answers2

2

You can pass a plain string to unset:

array1=(8 7 6 5 4 3 2 1)
X=1
unset "array$X[1]"
declare -p array1

results in the array without the second element (index 1):

declare -a array1=([0]="8" [2]="6" [3]="5" [4]="4" [5]="3" [6]="2" [7]="1")
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

If you really want to do it, I would combine the following two ideas:

delete by key:

$ realarray=( 5 4 3 2 1 "foo bar" ); ref=realarray; key=2
$ tmp=${ref}[@]; tmp=( "${!tmp}" )
$ unset "$ref"'['"$key"']'
$ echo "${realarray[@]}"
5 3 2 1 foo bar
$ echo "${#realarray[@]}"
5

delete by value:

$ realarray=( 5 4 3 2 1 "foo bar" ); ref=realarray; value=2
$ tmp=${ref}[@]; tmp=( "${!tmp}" )
$ eval "$ref=()"
$ for i in "${tmp[@]}"; do [ "$i" != "$value" ] && eval "$ref+=(\"$i\")"; done
$ echo "${realarray[@]}"
5 4 3 1 foo bar
$ echo "${#realarray[@]}"
5

This removes the element from the array and solves quoting issues. You could write this a bit different by using a second temporary and a single eval, but the idea is the same.

kvantour
  • 25,269
  • 4
  • 47
  • 72