Created
February 23, 2022 12:09
-
-
Save huevos-y-bacon/89fb87dc82622d5824132540b6c19c24 to your computer and use it in GitHub Desktop.
Bash - Arrays - Delete Elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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