3

I am using this code to check one $var if exists in array :

 if echo ${myArr[@]} | grep -qw $myVar; then echo "Var exists on array" fi

How could I combine more than one $vars to my check? Something like grep -qw $var1,$var2; then ... fi

Thank you in Advance.

3 Answers 3

1
if echo ${myArr[@]} | grep -qw -e "$myVar" -e "$otherVar"
then 
  echo "Var exists on array"
fi

From the man-page:

-e PATTERN, --regexp=PATTERN Use PATTERN as the pattern. This can be used to specify multiple search patterns, or to protect a pattern beginning with a hyphen (-). (-e is specified by POSIX.)

But if you want to use arrays like this you might as well use the bash built-in associative arrays.

To implement and logic:

myVar1=home1
myVar2=home2

myArr[0]=home1
myArr[1]=home2
if echo ${myArr[@]} | grep -qw -e "$myVar1.*$myVar2" -e "$myVar2.*$myVar1"
then 
          echo "Var exists on array"
fi

# using associative arrays

declare -A assoc
assoc[home1]=1
assoc[home2]=1

if [[ ${assoc[$myVar1]} && ${assoc[$myVar2]} ]]; then
  echo "Var exists on array"
fi
Sign up to request clarification or add additional context in comments.

2 Comments

Could be simplified like this: egrep -qw "$myVar|$otherVar"
This code is very close, but what if i want to make a conditional &&? myVar && otherVar (both must exists in Array) then "ok" else "not ok" ?
1

Actually you don't need grep for this, Bash is perfectly capable of doing Extended Regular Expressions itself (Bash 3.0 or later).

pattern="$var1|$var2|$var3"

for element in "${myArr[@]}"
do
    if [[ $element =~ $pattern ]]
    then
        echo "$pattern exists in array"
        break
    fi
done

Comments

0

Something quadratic, but aware of spaces:

myArr=(aa "bb c" ddd)

has_values(){ 
  for e in "${myArr[@]}" ; do
    for f ; do
      if [ "$e" = "$f" ]; then return 0 ; fi
    done
  done 
  return 1
}

if has_values "ee" "bb  c" ; then echo yes ; else echo "no" ; fi

this example will print no because "bb c" != "bb c"

1 Comment

This doesn't do regular expression matching, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.