Differences between revisions 1 and 6 (spanning 5 versions)
Revision 1 as of 2007-05-02 23:31:14
Size: 730
Editor: redondos
Comment:
Revision 6 as of 2008-11-22 21:42:30
Size: 821
Editor: GreyCat
Comment: first-line, and mention extglobs
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[Anchor(faq41)]] <<Anchor(faq41)>>
Line 3: Line 3:
In [[BASH]]:
Line 22: Line 23:
This should allow 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 [[glob|globbing]]-style patterns (including extended globs, if your shell offers them). If you need a portable way to match variables against [[RegularExpression|regular expressions]], use {{{grep}}} or {{{egrep}}}.
Line 25: Line 26:
  if echo "$foo" | egrep some-regex >/dev/null; then ...   if echo "$foo" | grep bar >/dev/null; then ...

How do I determine whether a variable contains a substring?

In BASH:

  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 (including extended globs, if your shell offers them). 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)