Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unterminated quoted string" when using variables with quotes in makefile

I have the following makefile:

help:
    @echo "MYVAR = $(MYVAR)"

Which if called works:

» MYVAR="hello" make -f makefile
MYVAR = xxx

But:

» MYVAR='"' make -f makefile 
/bin/sh: 1: Syntax error: Unterminated quoted string
makefile:2: recipe for target 'help' failed
make: *** [help] Error 2

How can I avoid that? Sometimes my variables have simply quotes inside (I deal with json very often)

like image 243
blueFast Avatar asked Oct 27 '25 04:10

blueFast


2 Answers

You have to escape quotation marks.

If you want to store '"' in a variable you have to assign '\"' to it.

And if you want to store " in a variable you have to assign \" to it.

like image 113
2501 Avatar answered Oct 28 '25 17:10

2501


If you want a completely generic quoting mechanism then you have to do this:

First, in your recipe you need to use single quotes around the content where the make variable is to be expanded. This is OK, because make doesn't care about quotes at all, and you need this because it means the only special character you have to worry about is a single quote.

Second, you have to translate all the single quotes in the string into the form '\'', which closes the current single quoted string, adds an escaped single quote, and starts a new single quoted string.

So, something like this:

quotestr = $(subst ','\'',$1)

help:
        @echo 'MYVAR = $(call quotestr,$(MYVAR))'

No matter what set of special characters you set MYVAR to, as long as it's used within single quotes, you shouldn't get any errors parsing it.

like image 36
MadScientist Avatar answered Oct 28 '25 17:10

MadScientist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!