1

Background

I am aware of bash's various string manipulation capabilities.

Also, I know I can escape special pattern characters with a backslash \.

For instance:

# x is a literal string 'foo*bar'
x="foo*bar"

# prints "*bar".
echo "${x##foo}"

# prints nothing, since the '*' is interpreted as a glob.
echo "${x##foo*}"

# prints "bar", since I escaped the '*'.
echo "${x##foo\*}"

The Problem

The above is all fine and dandy. The problem is when the pattern comes in from somewhere else, and it may not have the * and other special globbing characters escaped.

For example:

prefix="foo*"

... later, in some faraway code ...

x="foo*bar"
# I want this to print 'bar'. So I want the '*' to be escaped. But how?
echo "${x##$prefix}"

Essentially, I'm looking for something analogous to Perl's quotemeta function.

Is there something like this in bash?

jwd
  • 181
  • 7

1 Answers1

2

Ah, I figured this out just after posting.

The answer (as always) is: add more quotes (:

For my example:

prefix="foo*"

... later, in some faraway code ...

x="foo*bar"

# Prints 'bar' since the pattern has double-quotes surrounding it.
echo "${x##"$prefix"}"
jwd
  • 181
  • 7