Skip to main content

A few Bash helper functions for working with Arrays.

#!/usr/bin/env bash

#
# Array contains
#
# The only proper way to do this is by looping through each item. Other
# solutions claim to do this using string matching, but they are often
# dangerous because don't handle edge cases.
#
# Returns 0 if item is in the array; 1 otherwise.
#
# $1: The array value to search for
# $@: The array values, e.g. "${myarray[@]}"
#
# https://github.com/dansimau/bashlib/blob/master/bash.sh#L24
array_contains() {
    local item=$1
    shift
    for val in "$@"; do
        if [ "$val" == "$item" ]; then
            return 0
        fi
    done
    return 1
}

#
# Array filter
#
# Return all elements of an array with the specified item removed.
#
# $1: The array value to remove
# $@: The array values, e.g. "${myarray[@]}"
#
# https://github.com/dansimau/bashlib/blob/master/bash.sh#L42
array_filter() {
    local item=$1
    shift
    for val in "$@"; do
        if [ "$val" != "$item" ]; then
            echo $val
        fi
    done
}

#
# Array join
#
# Join array elements with a string.
#
# $1: String separator
# $@: Array elements
#
# https://github.com/dansimau/bashlib/blob/master/bash.sh#L59
array_join() {
    local sep=$1
    shift
    IFS=$sep eval 'echo "$*"'
}