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
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
```
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
```
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!
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"
```
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
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically