I have a variable which contain for example ['Cars', 'House', 'Bike']
. I want to be able to search for an exact match with values contained in the string.
Exemple:
- I check if the string
Cars
exist in the variable. It should returntrue
. - I check if the string
Car
exist in the variable. It should returnfalse
.
What I tried :
#!/bin/bash
search="Car"
arr="['Cars', 'House', 'Bike']"
if [[ $search =~ .*"$arr".* ]]; then
echo "true"
else
echo "false"
fi
# Output true | Expected false
Another script :
#!/bin/bash
search="Cars"
arr="['Cars', 'House', 'Bike']"
check=0
grep -o "'[^']*'" <<<"$arr" | sed "s/'//g" |
while read -r elem; do
if [ "$search" == "$elem" ]; then
check=1
fi
done
if [ "$check" == 1 ]; then
echo "true"
else
echo "false"
fi
# Output false | Expected true