Example:
absolute="/foo/bar"
current="/foo/baz/foo"
# Magic
relative="../../bar"
How do I create the magic (hopefully not too complicated code...)?
Example:
absolute="/foo/bar"
current="/foo/baz/foo"
# Magic
relative="../../bar"
How do I create the magic (hopefully not too complicated code...)?
Above shell script was inspired by pini's (Thanks!). It triggers a bug in the syntax highlighting module of Stack Overflow (at least in my preview frame). So please ignore if highlighting is incorrect.
Some notes:
Except for the mentioned backslash sequences the last line of function "relPath" outputs pathnames compatible to python:
Last line can be replaced (and simplified) by line
I prefer the latter because
Filenames can be directly appended to dir paths obtained by relPath, e.g.:
Symbolic links in the same dir created with this method do not have the ugly
"./"
prepended to the filename.Code listing for regression tests (simply append it to the shell script):
I would just use Perl for this not-so-trivial task:
Using realpath from GNU coreutils 8.23 is the simplest, I think:
For example:
Here is my version. It's based on the answer by @Offirmo. I made it Dash-compatible and fixed the following testcase failure:
./compute-relative.sh "/a/b/c/de/f/g" "/a/b/c/def/g/"
-->"../..f/g/"
Now:
CT_FindRelativePath "/a/b/c/de/f/g" "/a/b/c/def/g/"
-->"../../../def/g/"
See the code:
A slight improvement on kasku's and Pini's answers, which plays nicer with spaces and allows passing relative paths:
Guess this one shall do the trick too... (comes with built-in tests) :)
OK, some overhead expected, but we're doing Bourne shell here! ;)