Differences between revisions 8 and 9
Revision 8 as of 2010-11-29 22:24:01
Size: 1001
Editor: GreyCat
Comment: fixes, link to 100
Revision 9 as of 2013-07-24 15:32:42
Size: 1011
Editor: 188-223-3-27
Comment: grep is to match lines, not strings. Nowadays, you're more likely to want POSIX scripts than Bourne scripts
Deletions are marked like this. Additions are marked like this.
Line 20: Line 20:
If you are programming in the BourneShell instead of Bash, there is a more portable (but less pretty) syntax: If you are programming in the POSIX sh syntax or for the BourneShell instead of Bash, there is a more portable (but less pretty) syntax:
Line 24: Line 24:
  case "$foo" in   case $foo in
Line 29: Line 29:
{{{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}}}. {{{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 {{{expr}}}.

How do I determine whether a variable contains a substring?

In BASH:

  # Bash
  if [[ $foo = *bar* ]]

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

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

For more hints on string manipulations in Bash, see FAQ #100.

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

  # Bourne
  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 expr.

  # Bourne
  if echo "$foo" | grep bar >/dev/null 2>&1; then ...


CategoryShell

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