0

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
1
  • You have to consider three separate cases: arg is the first element, last element, or a middle element of the array. Even then, the whole point of an array is to store elements that might contain whatever delimiter ${...[*]} uses to construct a single string. Just use the for loop. If speed is an issue, you should absolutely not be using bash in the first place. Commented Sep 30, 2022 at 19:44

1 Answer 1

6

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! So, there's no one line trick to do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.