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

command linelinuxpathshell

We have two paths. First one is directory, second either a directory or a file.

/a/b/c and /a/d/e.txt

Relative path from first path to second will be:

../../d/e.txt

How to calculate that in Linux terminal? For those who ask “What is usage case?” one could use this—for example—to create lots of relative symlinks.

Best Answer

Assuming GNU coreutils:

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

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

Related Question