How do I determine whether a variable contains a substring?

There are many choices here: you can perform an exact substring match, or a glob-style pattern match, or a RegularExpression match.

To match exact substrings, POSIX sh uses case:

# POSIX
case $bigvar in
    *substr*) ... ;;

If the substring is in a variable, and if an exact substring match is wanted, then the substring variable should be quoted:

# POSIX
case $bigvar in
    *"$substr"*) ... ;;

In Bash, you may also use the [[ command. It follows the same quoting semantics as case:

# Bash
if [[ $bigvar = *substr* ]]; then ...     # These are
if [[ $bigvar == *substr* ]]; then ...    # equivalent.

if [[ $bigvar = *"$substr"* ]]; then ...  # These are
if [[ $bigvar == *"$substr"* ]]; then ... # equivalent.

In both case and [[ you may also do glob-style pattern matching. Simply use unquoted glob characters in the pattern. If the pattern is in a variable, omit the double quotes, and it will be interpreted as a pattern instead of an exact substring.

# POSIX
case $filename in
    *.txt) ... ;;

pattern='*.txt'
case $filename in
    $pattern) ... ;;

# Bash
if [[ $filename = *.txt ]]; then ...
if [[ $filename == *.txt ]]; then ...

pattern='*.txt'
if [[ $filename = $pattern ]]; then ...
if [[ $filename == $pattern ]]; then ...

In Bash 3.x or later, [[ can also do Extended Regular Expression (ERE) matches using the =~ operator:

# Bash
# Matches ac, zabcz, xabbbbcq, etc.
re='ab*c'
if [[ $foo =~ $re ]]; then ...

Storing the regular expression in a variable and using =~ $variable is strongly recommended, as it avoids many undesirable surprises.

POSIX sh has no builtin regular expression matching, but you can call external programs such as expr or grep to do it.

# POSIX
# With expr, leading anchors are implied.
# An initial .* works around this.
if expr "$foo" : ".*$re" > /dev/null; then ...

# With grep, anchoring must be requested if desired.
if printf %s "$foo" | grep -q -- "$re"; then ...

expr uses Basic Regular Expressions (BRE); grep defaults to BRE, but may use ERE with the -E option.

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


CategoryShell

BashFAQ/041 (last edited 2025-04-11 03:27:15 by GreyCat)