V
V
vlarkanov2018-04-17 18:02:54
bash
vlarkanov, 2018-04-17 18:02:54

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

2 answer(s)
3
3vi1_0n3, 2018-05-14
@3vi1_0n3

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[@]}

In this form, array elements that have a space should not suffer, as in the variant from xibir

X
xibir, 2018-04-17
@xibir

maybe so
but first will become null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question