musteresel's blog


Get the path “up” from some file to some directory

2017-04-15

tagged: shell

Say you have some file foo/bar/baz.txt … and you want to know the path “up” from that file to the directory foo. In this example, this would be ../... For that I’m using the following in my Makefile:

path_up = realpath -m --relative-to $(abspath $(dir $@)) $(CURDIR)
# later used like:
$(shell $(path_up))

As a shell command outside of a Makefile this can look like this:

realpath -m --relative-to  $(dirname FILE) BASEDIR

Note that this is the realpath command from the GNU coreutils. As noted in this answer on UNIX Stack Exchange there are many different implementations of realpath with different features.