Differences between revisions 2 and 3
Revision 2 as of 2007-05-07 18:44:14
Size: 722
Editor: GreyCat
Comment: minor clean-up
Revision 3 as of 2007-08-30 03:34:37
Size: 726
Editor: GreyCat
Comment: link to globbing
Deletions are marked like this. Additions are marked like this.
Line 22: Line 22:
{{{case}}} allows you to match variables against globbing-style patterns. If you need a portable way to match variables against regular expressions, use {{{grep}}} or {{{egrep}}}. {{{case}}} allows you to match variables against [:globbing:]-style patterns. If you need a portable way to match variables against regular expressions, use {{{grep}}} or {{{egrep}}}.

Anchor(faq41)

How do I determine whether a variable contains a substring?

  if [[ $foo = *bar* ]]

The above works in virtually all versions of Bash. Bash version 3 also allows regular expressions:

  if [[ $foo =~ ab*c ]]   # bash 3, matches abbbbcde, or ac, etc.

If you are programming in the BourneShell instead of Bash, there is a more portable (but less pretty) syntax:

  case "$foo" in
    *bar*) .... ;;
  esac

case allows you to match variables against [:globbing:]-style patterns. If you need a portable way to match variables against regular expressions, use grep or egrep.

  if echo "$foo" | grep bar >/dev/null; then ...

BashFAQ/041 (last edited 2013-07-24 15:34:17 by 188-223-3-27)