Chris G.
Chris G.

Reputation: 25974

How to get parent dir in Makefile

This is printing the current dir, not the parent:

run:
    @cd ..; \
    echo $(shell pwd)

I need the parent dir in a command like:

run:
    @cd ..; \
    docker run -it --rm -p 8080:8080 -v $(shell pwd):/go/src/hello golang bash

Upvotes: 0

Views: 2360

Answers (2)

Jens
Jens

Reputation: 72737

Why not use the POSIXly mandated variable PWD?

run:
    @cd ..; echo $$PWD

Save a process today!

Upvotes: 2

MadScientist
MadScientist

Reputation: 101011

Remember that make works by invoking a shell and sending the recipe to the shell for execution. Make doesn't have a shell "built in", so it's not running recipes directly.

The problem is that $(shell ..) is a make function. All make variables and functions are expanded before the shell is invoked (consider: the shell doesn't know how to handle make functions).

That means that a make function like $(shell ...) is first expanded and pwd is run, which gives you the current directory that the make process is running in, then the resulting string is passed to the shell for execution. So the shell sees this:

cd ..; echo /path/to/make/dir

You never need to use the $(shell ...) function inside a recipe; the recipe is already running in a shell! Instead you want to use shell syntax inside a recipe. The one caveat to this is that you have to escape dollar signs (replacing shell $ with $$) so that make doesn't interpret them as make variables. So if you write:

run:
    @cd ..; echo $$(pwd)

then make expands that string and sends this command to the shell:

cd ..; echo $(pwd)

which works as you want.

Upvotes: 2

Related Questions