Determine if a Bash variable is one of several values

Suppose that there are three possible values for the variable Bash $x: foo, barand baz. How to write an expression to determine if $xone of these values ​​is? In Python, for example, you can write:

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

Is there a Bash equivalent, or do three comparisons need to be done? Again, in Python you can write:

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

What is the correct way to express above in Bash?

+4
source share
3 answers

The simplest way:

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

Bit harder

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

More difficult:

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
+5
source

Use the case statement:

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

|| [[ ]]:

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

Source: https://habr.com/ru/post/1536247/


All Articles