Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

shell - How to use Bash parameter substitution in a Makefile?

I've the following Makefile where I'd like to use Bash parameter substitution syntax as below:

SHELL:=/bin/bash
Foo=Bar
all:
  @echo ${Foo}
  @echo ${Foo/Bar/OK}

However it doesn't work as expected, as the output of the second echo command is empty:

$ make
Bar
(empty)

Although it works fine when invoking in shell directly:

$ Foo=Bar; echo ${Foo/Bar/OK}
OK

How can I use the above syntax in Makefile?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want the shell to expand the variable you have to use a shell variable, not a make variable. ${Foo/Bar/OK} is a make variable named literally Foo/Bar/OK.

If you want to use shell variable substitution you'll have to assign that value to a shell variable:

all:
        Foo='$(Foo)'; echo $${Foo/Bar/OK}

Note that we use the double-dollar $$ to escape the dollar sign so that make doesn't try to expand it.

I strongly recommend you don't add @ to your rules until you're sure they work. It's the single most common mistake I see; if people would just not use @ they could see the command make is invoking, and then they would better understand how make works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...