GNU make equivalent to BSD make's $(var:Q)?

484 Views Asked by At

BSD make has a :Q variable expansion modifier, documented in the FreeBSD make man page as follows:

:Q   Quotes every shell meta-character in the variable, so that it can be
     passed safely through recursive invocations of make.

If variable var has value a b\c"d'e$f, then $(var:Q) expands to a\ b\\c\"d\'e\$f (or something equivalent). This is useful to pass strings to the shell without worrying that the shell will interpret any special characters.

Does GNU make have an equivalent? Or do I have to escape special characters my own?

2

There are 2 best solutions below

1
On BEST ANSWER

GNU make provides functions subst and patsubst which can help solve the problem. Those are more general, but require more work by the developer since they do not solve the specific problem. Also, the documentation does not show they use regular expressions, adding to the work.

For instance, you could in principle build up an expression like this:

$(subst \\,\\\\,$(subst ",\", $(subst ',\', var)))

For more discussion,

0
On

For sh variants, simply encase the expression in single quotes, changing any embedded single quote into '"'"'.

quote = '$(subst ','"'"',$1)'

Usage:

$(error [$(call quote,ab'c\ d$$f)])

Footnote: There is no way to quote anything inside single quotes. A second single quote thus closes the quoted expression. So, to handle an embedded single quote, close the single quotes with ', add a quoted single quote "'", start another single-quoted string '.