anol
anol

Reputation: 8953

Add suffix to string only if not already present

In a (GNU) Makefile, I want to add an optional DESTDIR prefix to a path (which may or may not be absolute), as in:

I want in all cases the resulting ${DESTDIR} + ${DIR} concatenation to be a valid path and without double slashes. That is:

The following does seem to work (at least on a few tests):

ifeq (${DESTDIR},)
# DESTDIR is empty
FULLDIR:=${DIR}
else
ifeq ($(patsubst %/,$,${DESTDIR}),${DESTDIR})
# DESTDIR has no trailing slash
FULLDIR:=${DESTDIR}/${DIR}
else
# DESTDIR has a trailing slash
FULLDIR:=${DESTDIR}${DIR}
endif
endif
$(info FULLDIR: ${FULLDIR})

But it is very cumbersome. Is there a simpler/shorter way to obtain the same results?

Upvotes: 0

Views: 411

Answers (2)

HardcoreHenry
HardcoreHenry

Reputation: 6377

FULLDIR := $(if ${DESTDIR},$(patsubst %/,%,${DESTDIR})/${DIR},${DIR})

Upvotes: 1

jimnwq
jimnwq

Reputation: 60

GNU Make has some built-in functions to manipulate file names.

Ones in your interest might be $(abspath *files...*) and $(realpath *files...*).

Both functions will take your path and convert it to canonical absolute path, which is absolute path without repeating slash, .. and .. Only difference is that realpath will resolve symlinks but abspath will not.

Though if you want something not absolute path, only thing I can tell is there's no easy way for it. One may try creating regex that replaces repeating slash into one and use $(shell) function with regex command line utility, but it will still contain a lot of ambiguity like having .. or three slashes in a row.

So my recommendation is to do $(realpath ${DESTDIR}/${DIR}).

Upvotes: 2

Related Questions