Check if a variable exists in a list in Bash

I am trying to write a script in bash that check the validity of a user input.
I want to match the input (say variable x) to a list of valid values.

what I have come up with at the moment is:

for item in $list
do
    if [ "$x" == "$item" ]; then
        echo "In the list"
        exit
    fi
done

My question is if there is a simpler way to do this,
something like a list.contains(x) for most programming languages.

Say list is:

list="11 22 33"

my code will echo the message only for those values since list is treated as an array and not a string,
all the string manipulations will validate 1 while I would want it to fail.

19 Answers
19

Leave a Comment