Bagels1b
Bagels1b

Reputation: 61

Search bash array for a substring of an element

I am trying to use bash to check if any substring in a user input (arg) is in an array of keywords. I can successfully check for the whole string but so far I haven't been able to check for the substring. The code below works for matching the whole string (arg) against members of the keyword_array. Is there a way to tweak my 'if' check so that any string the user inputs that contains "branch" or "switch" will match? I've tried adding *'s in various places and did " ${arg} " =~ " ${keyword_array[*]} " with no luck. I can do this with a for loop but I'm trying to see if there's a way to do it similar to the check that matches the entire string.

keyword_array=("branch" "switch")
arg="switch test"  # This won't match
#arg="switch"  # This matches

if [[ " ${keyword_array[*]} " =~ " ${arg} " ]] ; then
    echo "arg matches"
else
    echo "arg does not match"
fi

Upvotes: 0

Views: 96

Answers (1)

glenn jackman
glenn jackman

Reputation: 246797

I'd use an associative array to store the keywords, split the user input into separate words, and loop over that:

# we only need to keywords as array keys, the value doesn't matter
declare -A keywords=([branch]= [switch]=)

arg="switch test"
read -ra words <<<"$arg"

ok=true
for word in "${words[@]}"; do
    if [[ -v "keywords[$word]" ]]; then   
        echo "found a keyword: $word"
        ok=false
        break
    fi
done
$ok && echo "arg is ok"

Upvotes: 6

Related Questions