Check if a variable exists in a list in Bash

[[ $list =~ (^|[[:space:]])$x($|[[:space:]]) ]] && echo 'yes' || echo 'no'

or create a function:

contains() {
    [[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && exit(0) || exit(1)
}

to use it:

contains aList anItem
echo $? # 0: match, 1: failed

Leave a Comment