ʞɔıu
ʞɔıu

Reputation: 48416

In array operator in bash

Is there a way to test whether an array contains a specified element?

e.g., something like:

array=(one two three)

if [ "one" in ${array} ]; then
...
fi

Upvotes: 15

Views: 10911

Answers (10)

maxlen
maxlen

Reputation: 13

#! /bin/bash

envs=("production" "prod" "stage" "test" "dev");
APP_ENV="prod"

if [[ ${envs[*]} =~ $APP_ENV ]]
then
  echo "value found"
else
  echo "value not found"
fi

Upvotes: 0

x-yuri
x-yuri

Reputation: 18873

in_array() {
    local needle=$1 el
    shift
    for el in "$@"; do
        if [ "$el" = "$needle" ]; then
            return 0
        fi
    done
    return 1
}

if in_array 1 1 2 3; then
    echo true
else
    echo false
fi

# alternatively
a=(1 2 3)
if in_array 1 "${a[@]}"; then
...

Upvotes: 0

ayoub etters
ayoub etters

Reputation: 1

OPTIONS=('-q','-Q','-s','-S')

find="$(grep "\-q" <<< "${OPTIONS[@]}")"
if [ "$find" = "${OPTIONS[@]}" ];
then
    echo "arr contains -q"
fi

Upvotes: -1

Sz&#233;pe Viktor
Sz&#233;pe Viktor

Reputation: 348

In_array() {
    local NEEDLE="$1"
    local ELEMENT

    shift

    for ELEMENT; do
        if [ "$ELEMENT" == "$NEEDLE" ]; then
            return 0
        fi
    done

    return 1
}

declare -a ARRAY=( "elem1" "elem2" "elem3" )
if In_array "elem1" "${ARRAY[@]}"; then
...

A nice and elegant version of the above.

Upvotes: 0

Frank
Frank

Reputation: 661

A for loop will do the trick.

array=(one two three)

for i in "${array[@]}"; do
  if [[ "$i" = "one" ]]; then
    ...
    break
  fi
done

Upvotes: 25

William Pursell
William Pursell

Reputation: 212268

I like using grep for this:

if echo ${array[@]} | grep -qw one; then
  # "one" is in the array
  ...
fi

(Note that both -q and -w are non-standard options to grep: -w tells it to work on whole words only, and -q ("quiet") suppresses all output.)

Upvotes: 2

user unknown
user unknown

Reputation: 36229

I got an function 'contains' in my .bashrc-file:

contains () 
{ 
    param=$1;
    shift;
    for elem in "$@";
    do
        [[ "$param" = "$elem" ]] && return 0;
    done;
    return 1
}

It works well with an array:

contains on $array && echo hit || echo miss
  miss
contains one $array && echo hit || echo miss
  hit
contains onex $array && echo hit || echo miss
  miss

But doesn't need an array:

contains one four two one zero && echo hit || echo miss
  hit

Upvotes: 8

pepoluan
pepoluan

Reputation: 6780

Try this:

array=(one two three)
if [[ "${array[*]}" =~ "one" ]]; then
  echo "'one' is found"
fi

Upvotes: 7

ghostdog74
ghostdog74

Reputation: 342433

if you just want to check whether an element is in array, another approach

case "${array[@]/one/}" in 
 "${array[@]}" ) echo "not in there";;
 *) echo "found ";;
esac

Upvotes: 0

drysdam
drysdam

Reputation: 8637

array="one two three"
if [ $(echo "$array" | grep one | wc -l) -gt 0 ] ; 
  then echo yes; 
fi

If that's ugly, you could hide it away in a function.

Upvotes: 0

Related Questions