I need to remove an element from an array in bash shell. Generally I'd simply do:
array=("${(@)array:#<element to remove>}")
Unfortunately the element I want to remove is a variable so I can't use the previous command. Down here an example:
array+=(pluto)
array+=(pippo)
delete=(pluto)
array( ${array[@]/$delete} ) -> but clearly doesn't work because of {}
Any idea?
Here's a one-line solution with mapfile:
Example:
This method allows for great flexibility by modifying/exchanging the grep command and doesn't leave any empty strings in the array.
Actually, I just noticed that the shell syntax somewhat has a behavior built-in that allows for easy reconstruction of the array when, as posed in the question, an item should be removed.
Notice how we constructed the array using bash's
x+=()
syntax?You could actually add more than one item with that, the content of a whole other array at once.
You could build up a new array without the undesired element, then assign it back to the old array. This works in
bash
:This yields:
This is the most direct way to unset a value if you know it's position.
Partial answer only
To delete the first item in the array
To delete the last item in the array