How can I check if a variable is in a list in Bash?

0
13
Asked By CleverRaccoon42 On

I'm working with a Bash script and I have a list defined like this: `mylist=("foo" "bar" "baz")`. I want to find out if a variable, say `$var`, is in that list without using a loop. Is there a way to do this more efficiently?

5 Answers

Answered By QuirkyDolphin88 On

You can definitely do it in a more streamlined way. One option is to use a function that wraps a loop without being too cumbersome. Check this out:

```bash
is_in_list() {
local needle=$1
shift
while (( $# )) && [[ $1 != "$needle" ]]; do
shift
done
(( $# ))
}
```

Usage:

```bash
$ is_in_list foo foo bar baz; echo $?
0
$ is_in_list quux foo bar baz; echo $?
1
```

Answered By SassyPenguin19 On

Here's a simple way to check if your variable exists in the list without a loop:

```bash
if printf "%sn" "${mylist[@]}" | grep -qxF -- "$var"; then
echo "available"
else
echo "not available"
fi
```

Answered By BubblyEagle23 On

Another neat trick is using regex with the `=~` operator:

```bash
items=("apple" "banana" "cherry")
search="banana"
if [[ " ${items[*]} " =~ " ${search} " ]]; then
echo "Found it!"
fi
```
Just keep in mind that regex can be a bit tricky!

Answered By PlayfulTurtle11 On

Using a loop can be a good idea to avoid external commands! Here's a straightforward example:

```bash
list=('foo' 'bar' 'baz')
var=$1
for item in "${list[@]}"; do
if [[ $item == "$var" ]]; then
echo "'$var' found"
exit 0
fi
done

echo "'$var' not found"
```

Answered By GigglyOstrich77 On

You can also use the following:

```bash
var=bar; mylist=("foo" "bar" "baz"); [[ " ${mylist[*]} " = * $var * ]]; echo $?
```

Or this alternative using variable comparison:
```bash
[[ ${mylist[*]} != ${mylist[*]//${var}/} ]]
```
Just a heads up, this works for words only!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.