Help with if statement syntax

Hi,

Is there a way to compare the value in if condition with a list of values.

eg . if [[ $a in cat,dog,horse ]]
      then
      echo "it's a mammal"
      else
      echo "its not"
      fi

Thanks!

Hi

No, you cannot do this way in shell.

if [ $a = "cat" -o $a = "dog" -o $a = "horse" ];
.....

Guru.

if the values are in array variable means how can we check for each... ?

Please suggest the another method to compare the array variable in if condition.

Hi
In shell, to check for a specific element in an array, you have to traverse element by element to check it. This is where awk or perl helps in making the search easy.

Looking for something like this?

#!/bin/bash
array=( cat dog horse )

a="horse"

for x in ${array[@]}
do
    if [ "$a" == "$x" ]
    then
        echo "$a and $x match"
    else
        echo "$a and $x do not match"
    fi
done
1 Like

Any Posix shell:

case statement:

case $a in 
   (cat|dog|horse) echo "it's a mammal";;
   (*)             echo "its not, since the only mammals known to mankind are cats, dogs and horses.."
esac

Or with individual tests:

if [ "$a" = cat ] || [ "$a" = dog ] || [ "$a" = horse ] 

---
bash/ksh specific:

if [[ "$a" == cat || "$a" == dog || "$a" == horse ]]

--
modern bash / ksh93

if [[ "$a" =~ ^(cat|dog|horse)$ ]]

Hi ,

Thanks for your replies, here's what I got working

animals="dog,cat,horse"
if [[ "${animal}" == *${mammal}* ]]

The reason behind adopting this kind of approach is because, i wanted to implement a list with atleast 10 elements being looked at. The "or" approach is just too cumbersome IMHO.

Thanks anyways.

Thanks.

Hi, neil, what does $mammal contain and what does $animal contain and how does that relate to $animals ?

--
ksh93 / modern bash, associative arrays:

a=cat
A=([cat]=1 [dog]=1 [horse]=1)                                       
if [[ ${A[$a]} ]]; then...

or:

a=cat
A=([cat]= [dog]= [horse]=)                                       
if [[ ${A[$a]+_} ]]; then...