Skip to content

Instantly share code, notes, and snippets.

@huevos-y-bacon
Created February 23, 2022 12:09
Show Gist options
  • Save huevos-y-bacon/89fb87dc82622d5824132540b6c19c24 to your computer and use it in GitHub Desktop.
Save huevos-y-bacon/89fb87dc82622d5824132540b6c19c24 to your computer and use it in GitHub Desktop.
Bash Arrays - Delete Elements
#!/usr/bin/env bash
# see: https://stackoverflow.com/questions/16860877/remove-an-element-from-a-bash-array
array=(pluto pippo bob john 1 56)
echo "array: ${array[*]}"
echo
delete=(pippo 56)
echo "delete: ${delete[*]}"
for target in "${delete[@]}"; do
for i in "${!array[@]}"; do
if [[ ${array[i]} = $target ]]; then
unset 'array[i]'
fi
done
done
echo "array: ${array[*]}"
echo
echo "This creates gaps:"
declare -p array
# declare -a array=([0]="pluto" [2]="bob")
echo
echo "Rebuild the array:"
array=("${array[@]}")
declare -p array
# declare -a array='([0]="pluto" [1]="bob")'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment