Search code examples
shellmakefile

Using $PWD to get parent directory's basename in makefile


I need to automate a variable alignment in my Makefile. My Makefile's full file path is:

/home/e2/branchname/projectname/modulename/Makefile

In my Makefile, I have a variable BUILD_DIR, a part of which should be equal to the branchname in the full path.

So I did this:

BRANCH_NAME= $(shell cd ../.. && basename "$PWD" && cd projectname/modulename)
BUILD_DIR=$(HOME)/$(BRANCH_NAME)/build

Apparently I expected BUILD_DIR to be ~/branchname/build here, but after make I got ~/WD/build instead. I think it's most likely that I got a wrong BRANCH_NAME. Is there something wrong with what I did? And if yes I'd like to get some advice about how to do it correctly.

Thanks.


Solution

  • It's because $ has a special meaning to Make, so if you want to pass that up to shell you have to "escape" it. In case of Make, you escape the dollar sign by doubling. So you have to use $$PWD.

    Also, what you are doing is not really the best way - it is always best to avoid the shell and use Make functionality if possible. In your case, the best way to do what you want is this:

    BUILD_DIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))/../../build)
    

    You have to put the above line in the makefile in question, near the top, so that it is before you include any other makefiles.