Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether Bash variable is one of several values

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?

like image 668
davidchambers Avatar asked Apr 12 '14 17:04

davidchambers


Video Answer


2 Answers

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
like image 173
glenn jackman Avatar answered Nov 18 '22 10:11

glenn jackman


Use a case statement:

var=bar
case $var in
  foo | bar | baz )
    echo "Matches"
    ;;
esac
like image 37
that other guy Avatar answered Nov 18 '22 08:11

that other guy