Bootstrap FreeKB - Bash (Scripting) - Remove values from a list
Bash (Scripting) - Remove values from a list

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


list=("${list[@]/banana}")
echo AFTER = ${list[@]}

 

Which should print the following.

BEFORE = apple banana orange grapes pineapple
AFTER  = apple orange grapes 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".

BEFORE = apple banana orange grapes pineapple
AFTER  = banana orange grapes pine

 

So it's much better to go wtih unset.

#!/bin/bash
list=(orange banana apple grapes pineapple)
echo BEFORE = ${list[@]}

for index in "${!list[@]}"; do
  if [[ ${list[index]} = "orange" ]]; then
    unset list[index]
  fi
done

echo AFTER = ${list[@]}

 

So that "apple" is removed and "pineapple" is not changed.

BEFORE = orange banana apple grapes pineapple
AFTER  = orange banana grapes pineapple

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 35810a in the box below so that we can be sure you are a human.