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?

1
  • Do you want to keep the original indices? Commented Dec 20, 2019 at 18:10

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

5 Comments

This is exactly what I needed. Thank you!) By the way, how I can add value to array$X?
@БулатХайруллин declare "array$X[42]=1337"
When I do it like this: eval array$X+=${array[-1]} array$X will have 1 eval array$X+=${array[-2]} array$X will have 12 instead of 1 2 eval array$X+=${array[-3]} array$X will have 123 instead of 1 2 3
I need to add value to the end of array$X
declare "array$X+=(42)"
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.