How to calculate a relative path from two absolute paths in Linux shell?

Solution 1:

Assuming GNU coreutils:

  • For symlinks, ln has recently learned the --relative option.

  • For everything else, realpath supports options --relative-to= and --relative-base=.

Solution 2:

For me, this answer (which uses a python oneliner) works perfect.

$ python -c "import os.path; print os.path.relpath('/a/d/e.txt', '/a/b/c')"
../../d/e.txt

Tested successfully on linux (Kubuntu 14.04) an on Mac OSX, needs Python 2.6.