18

Assume there are three valid values for a Bash variable $x: foo, bar, and baz. How does one write an expression to determine whether $x is one of these values? In Python, for example, one might write:

x in ('foo', 'bar', 'baz')

Is there a Bash equivalent, or is it necessary to perform three comparisons? Again, in Python, one could write:

x == 'foo' or x == 'bar' or x == 'baz'

What's the correct way to express the above in Bash?

3 Answers 3

25

Simplest way:

case $x in
    foo|bar|baz) echo is valid ;;
    *) echo not valid ;;
esac

A bit more complicated

shopt -s extglob
if [[ $x == @(foo|bar|baz) ]]; then
    echo is valid
else
    echo not valid
fi

More complicated:

is_valid() {
    local valid=( foo bar baz )
    local value=$1
    for elem in "${valid[@]}"; do
        [[ $value == $elem ]] && return 0
    done
    return 1
}

if is_valid "$x"; then
    echo is valid
else
    echo not valid
fi
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know about shopt -s extglob. Thanks!
And in this context, it's not required: from the manual "When the ‘==’ and ‘!=’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching, as if the extglob shell option were enabled."
9

One can use || for alternation between [[ and ]]:

if [[ $x == foo || $x == bar || $x == baz ]] ; then
  echo valid
else
  echo invalid
fi

1 Comment

+1, but note that not quoting the right operands means they're interpreted not as literals, but as patterns (globs) - no difference in this specific case, but it's important to be aware of the distinction.
8

Use a case statement:

var=bar
case $var in
  foo | bar | baz )
    echo "Matches"
    ;;
esac

1 Comment

How could i miss that one. Of course it's the good way do do it. +1

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.