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...)?
My Solution:
Presuming that you have installed: bash, pwd, dirname, echo; then relpath is
I've golfed the answer from pini and a few other ideas
Not a lot of the answers here are practical for every day use. Since it is very difficult to do this properly in pure bash, I suggest the following, reliable solution (similar to one suggestion buried in a comment):
Then, you can get the relative path based upon the current directory:
or you can specify that the path be relative to a given directory:
The one disadvantage is this requires python, but:
Note that solutions which include
basename
ordirname
may not necessarily be better, as they require thatcoreutils
be installed. If somebody has a purebash
solution that is reliable and simple (rather than a convoluted curiosity), I'd be surprised.It is built in to Perl since 2001, so it works on nearly every system you can imagine, even VMS.
Also, the solution is easy to understand.
So for your example:
...would work fine.
This script gives correct results only for inputs that are absolute paths or relative paths without
.
or..
:This is a corrected, fully functional improvement of the currently best rated solution from @pini (which sadly handle only a few cases)
Reminder : '-z' test if the string is zero-length (=empty) and '-n' test if the string is not empty.
Test cases :