check if a string contains a text

Test in a script whether a string contains, starts with or matches something.

  • shell
  • development

Steps

  1. [[ $text == *"needle"* ]] && echo found

    contains needle

  2. [[ $text == prefix* ]] && echo yes

    starts with prefix

  3. [[ $text =~ ^[0-9]+$ ]] && echo 'a number'

    matches a regular expression

  4. grep -q 'needle' <<< "$text" && echo found

    with grep, also in sh

  5. [[ -z $text ]] && echo empty

    is empty

Notes

  • [[ ]] is bash and zsh; in plain sh use case or grep.

Commands used

  • grep

Each has a page in lore: lore grep opens it.