Check if a variable exists in a list in Bash
how about
echo $list | grep -w -q $x
you could either check the output or $?
of above line to make the decision.
grep -w
checks on whole word patterns. Adding -q
prevents echoing the list.
[[ $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