Skip to content

Instantly share code, notes, and snippets.

@apolopena
Last active April 8, 2022 20:19
Show Gist options
  • Save apolopena/edab24c2abb7f220b0ac5575a211a238 to your computer and use it in GitHub Desktop.
Save apolopena/edab24c2abb7f220b0ac5575a211a238 to your computer and use it in GitHub Desktop.
Bash: remove an element from an array

Remove an element from an array

Arrays in bash were not designed for use as mutable data structures. They are primarily used for storing lists of items in a single variable without needing to waste a character as a delimiter (e.g., to store a list of strings which can contain whitespace). We can however remove an element from an array by looping through the array and rebuilding it as a temporary array, set the array to the temporary array and then finally unset the temporary array.

#!/bin/bash

example() {
 local i args tmp_args=()
 args=("$@")
 echo "${#args[@]} args before the filter: ${args[*]}"
 if  [[ " ${args[*]} " =~ " --load-deps-locally " ]]; then
   for i in "${args[@]}"; do [[ $i != '--load-deps-locally' ]] && tmp_args+=("$i"); done
 fi
 args=("${tmp_args[@]}"); unset tmp_args
 echo "${#args[@]} args after the filter: ${args[*]}"
}

example foo bar baz --load-deps-locally foobarbaz
# Outputs:
#   5 args before the filter: foo bar baz --load-deps-locally foobarbaz
#   4 args after the filter: foo bar baz foobarbaz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment