Size: 821
Comment: first-line, and mention extglobs
|
Size: 844
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 28: | Line 28: |
---- CategoryShell |
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 ...