Bash (Scripting) - Remove values from a list

by
Jeremy Canfield |
Updated: August 25 2024
| Bash (Scripting) articles
If you are not familiar with lists, check out our article Getting Started with Lists in Bash Shell Scripting.
Let's say you have an list of fruit. Here is an example of how you can remove "banana" from the list.
#!/bin/bash
list=(apple banana orange grapes pineapple)
echo BEFORE = ${list[@]}
declare -p list
list=("${list[@]/banana}")
echo AFTER = ${list[@]}
declare -p list
Which should print the following. Notice that this does not actually remove the element from the list but instead updates the element in the list to have no value.
BEFORE = apple banana orange grapes pineapple
declare -a list=([0]="apple" [1]="banana" [2]="orange" [3]="grapes" [4]="pineapple")
AFTER = apple orange grapes pineapple
declare -a list=([0]="apple" [1]="" [2]="orange" [3]="grapes" [4]="pineapple")
Let's say you want to remove "apple".
#!/bin/bash
list=(apple banana orange grapes pineapple)
echo BEFORE = ${list[@]}
list=("${list[@]/apple}")
echo AFTER = ${list[@]}
This will remove "apple" but also change "pineapple" to "pine" because this just removes "apple" from each key in the list.
BEFORE = apple banana orange grapes pineapple
AFTER = banana orange grapes pine
So it's much better to go with unset because this actually removes the index from the list.
#!/bin/bash
list=(orange banana apple grapes pineapple)
echo BEFORE = ${list[@]}
declare -p list
for index in "${!list[@]}"; do
if [[ ${list[index]} = "orange" ]]; then
unset list[index]
fi
done
echo AFTER = ${list[@]}
declare -p list
So that "apple" is removed and "pineapple" is not changed.
BEFORE = orange banana apple grapes pineapple
declare -a list=([0]="orange" [1]="banana" [2]="apple" [3]="grapes" [4]="pineapple")
AFTER = banana apple grapes pineapple
declare -a list=([1]="banana" [2]="apple" [3]="grapes" [4]="pineapple")
Did you find this article helpful?
If so, consider buying me a coffee over at