[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to assign a shell variable in a makefile?

From: Paul Smith
Subject: Re: How to assign a shell variable in a makefile?
Date: Sun, 11 Apr 2010 01:59:02 -0400

On Sat, 2010-04-10 at 22:07 -0500, Peng Yu wrote:
> I want assigned the variable something in shell some value and then echo it.
> ########
> .PHONY: all
> all:
>       something=$(shell basename abc.txt .txt)
>       echo $(something)
>       echo $$(something)
> ################
> But the above code doesn't work. Would you please let me know what the
> correct way is to assign a shell variable and retrieve it?

There are a LOT of problems here.  First please keep very clearly in
your mind the distinction between what is interpreted by make and what
is interpreted by the shell.

Remember that ALL make operations happen first, then the fully-expanded
string is passed to the shell and ALL shell operations happen afterward.
There is no "interaction" back to make from the shell: make invokes the
command and waits for it to exit, and that's it.  Since make evaluates
the string first, any dollar sign you want to be passed to the shell
must be escaped as "$$".

Second, remember that shell syntax is not the same as make syntax.  In
the shell, variable references can be written as either $foo or ${foo},
but never $(foo).

And finally, remember that make invokes a completely new shell for every
logical line of the recipe.  So a shell is invoked for the first line,
then after that exits a different shell is invoked for the second line,
etc.  Because in UNIX a process can never modify the environment of its
parent, this means that shell settings, changes of directory, etc. that
occur in one shell, which then exits, can never be seen in the next
shell.  So if you set a shell variable in one logical line of a recipe,
that variable assignment will have disappeared when you get to the next
logical line.

All that being said, you probably want this:

                something=`basename abc.txt .txt`; \
                    echo $$something

There are lots of other ways you can do this, including much more
efficient ways using either make functions or shell variable modifiers,

 Paul D. Smith <address@hidden>          Find some GNU make tips at:            
 "Please remain calm...I may be mad, but I am a professional." --Mad Scientist

reply via email to

[Prev in Thread] Current Thread [Next in Thread]