Differences between revisions 3 and 12 (spanning 9 versions)
Revision 3 as of 2007-08-30 03:34:37
Size: 726
Editor: GreyCat
Comment: link to globbing
Revision 12 as of 2025-04-10 21:11:07
Size: 957
Editor: 81
Comment: Streamline code
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[Anchor(faq41)]] <<Anchor(faq41)>>
Line 3: Line 3:
Pattern matching in [[BASH]]:
Line 5: Line 6:
  if [[ $foo = *bar* ]]   # Bash
if [[ $foo == *bar* ]]
Line 8: Line 10:
The above works in virtually all versions of Bash. Bash version 3 also allows regular expressions: Bash also supports regular expressions:
Line 11: Line 13:
  if [[ $foo =~ ab*c ]] # bash 3, matches abbbbcde, or ac, etc.   # Bash 3.x
  # matches e.g ac, abc and abbbbc
  re='ab*c'
  if [[ $foo =~ $re ]]
Line 14: Line 19:
If you are programming in the BourneShell instead of Bash, there is a more portable (but less pretty) syntax: For more hints on string manipulations in Bash, see [[BashFAQ/100|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:
Line 17: Line 24:
  case "$foo" in   # Bourne
case $foo in
Line 22: Line 30:
{{{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 [[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}}}.
Line 25: Line 33:
  if echo "$foo" | grep bar >/dev/null; then ...   # Bourne/POSIX
if expr "x$foo" : 'x.*bar' >/dev/null; then ...
Line 27: Line 36:

----
CategoryShell

How do I determine whether a variable contains a substring?

Pattern matching in BASH:

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

Bash also supports regular expressions:

  # Bash 3.x
  # matches e.g ac, abc and abbbbc
  re='ab*c'
  if [[ $foo =~ $re ]]   

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/POSIX
  if expr "x$foo" : 'x.*bar' >/dev/null; then ...


CategoryShell

BashFAQ/041 (last edited 2025-04-19 15:51:39 by StephaneChazelas)