Bash: Check if array element exists

From FVue
Jump to: navigation, search

Problem

Within bash, I want to check if an array contains a specific element.

Solution

Write a separate function in_array:

# Check if a value exists in an array
# @param $1 mixed  Needle  
# @param $2 array  Haystack
# @return  Success (0) if value exists, Failure (1) otherwise
# Usage: in_array "$needle" "${haystack[@]}"
# See: http://fvue.nl/wiki/Bash:_Check_if_array_element_exists
in_array() {
    local hay needle=$1
    shift
    for hay; do
        [[ $hay == $needle ]] && return 0
    done
    return 1
}

Tests:

$ aa=(foo bar "cee dee" eek "2 3" 34 4)
$ in_array bar       "${aa[@]}" && echo yes || echo no
yes
$ in_array cee       "${aa[@]}" && echo yes || echo no
no
$ in_array "cee dee" "${aa[@]}" && echo yes || echo no
yes
$ in_array 3         "${aa[@]}" && echo yes || echo no
no
$ in_array 4         "${aa[@]}" && echo yes || echo no
yes

Journal

2009

View topic - Testing Bash arrays for a string :: Linux Format :: The website of the UK's best-selling Linux magazine
Forum topic with 3 solutions in original question.

20110910

Timing different solutions.

for i in {0..10000}
do
    aa+=($i)
done
#echo \$array contains:
#declare -p aa
 
ss=5000
 
# @param $1 mixed  Needle  
# @param $2 mixed  Haystack
# @return  Success (0) if value exists, Failure (1) otherwise
in_array_for_loop() {
    local hay needle=$1
    shift
    for hay; do
        [[ $hay == $needle ]] && return 0
    done
    return 1
}
 
echo -n for_loop
time in_array_for_loop "$ss" "${aa[@]}" && echo yes || echo no
 
# @param $1 mixed  Needle  
# @param $2 mixed  Haystack
# @return  Success (0) if value exists, Failure (1) otherwise
in_array_for_loop_global() {
    shift
    for hay in "${aa[@]}"; do
        [[ "$hay" == "$ss" ]] && return 0
    done
    return 1
}
 
echo -n for_loop_global
time in_array_for_loop_global && echo yes || echo no
 
# @param $1 mixed  Needle  
# @param $2 mixed  Haystack
in_array_unset() {
    local haystack=("${@:2}")
    local bb=("${haystack[@]/$1/$1${1:-foo}}")
    [[ ${bb[@]} != ${haystack[@]} ]]
}
 
echo -n unset
time in_array_unset "$ss" "${aa[@]}" && echo yes || echo no

Comments

blog comments powered by Disqus