Get top-level directory from makefile variable

make

What is the simplest code to get the top-level directory part of a makefile variable? Example:

BUILD_DIR = dir/subdir/.../sub-a-dub-dir
distclean:
        rm -rf <some code which evaluates to "dir" from $(BUILD_DIR)>

PS: I don't mean $(dir $(dir $(BUILD_DIR))), but something which gets the first directory part of any variable value.

Best Answer

Do you mean the first component of the directory? If so, turn the path into a list of components, then extract the first component. I assume you're using GNU make, and you're not doing something insane like expect file names with whitespace to go through unscathed. Don't try this with an absolute path.

override BUILD_DIR = dir/subdir/.../sub-a-dub-dir
distclean:
        rm -rf $(firstword $(subst /, ,$(BUILD_DIR)))

I make BUILD_DIR override whatever the user might have passed on the command line, to avoid someone accidentally passing it and having something unintended deleted.

Related Question