Home > database >  echo a JSON environment variable in a makefile
echo a JSON environment variable in a makefile

Time:12-01

If I do this

user $ export JSON='
{
    "key":"val"
}
'

and then in my Makefile I do

.PHONY: test
test:
    @echo ${JSON}

I get the following error:

user $ make test

/bin/bash: -c: line 1: syntax error: unexpected end of file
make: *** [Makefile:166: test] Error 1

I guess I can do

user $ export JSON='{"key":"val"}'

and

.PHONY: test
test:
    @echo '${JSON}'

which works

CodePudding user response:

As you seem to have recognized, the problem is with the (lack of) quoting. In conjunction with that, it makes a difference whether you have make expand the variable reference or defer it for the shell to perform (which is an option for an environment variable, but not for a make variable). make expands the variable and then attempts to split the recipe into lines. The newlines in the variable's value interfere with that.

But for an environment variable such as this, you can work around a variety of problems by deferring expansion to the shell by escaping the $ to make:

.PHONY: test
test:
    @echo "$${JSON}"

The $$ represents a literal $ to make, and suppresses expansion of variable JSON. The resulting shell command contains a double-quoted expansion of the variable, which accommodates all manner of special characters in the variable's value, including newlines and double quotes.

  • Related