Answer the question
In order to leave comments, you need to log in
How to remove elements of an array so that it works like on a stack?
Let me explain.
There is an array array=( [1]=first [2]=second [3]=third [4]=forth [5]=fifth )
I want to remove the first element:
unset array[1]
If we display the array, we see that the first element missing:
second third forth fifth
BUT! If we force the output of the first element of the array, we see that it, although empty, is present in the array.
And here's my question: Is it possible to remove elements of an array in such a way that the remaining array is "reindexed" like this:
array[1]=second
array[2]=third
...
array[4]=fifth
?
Answer the question
In order to leave comments, you need to log in
1) Array elements in bash are numbered from 0
2) You can shift the values of all array elements to the left. Thus, for n elements, the nth element will be replaced by the (n+1)th element. It doesn't exist, so it will be empty. Here is an example:
#!/bin/bash
array=()
array[0]=first
array[1]=second
array[2]=third
array[3]=forth
echo ${array[@]}
for i in $(seq 0 $((${#array}-1)))
do
array[$i]=${array[$((i+1))]}
done
echo ${array[@]}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question