Convert absolute path into relative path given a current directory using Bash

Paul Tarjan picture Paul Tarjan · Apr 2, 2010 · Viewed 126.4k times · Source

Example:

absolute="/foo/bar"
current="/foo/baz/foo"

# Magic

relative="../../bar"

How do I create the magic (hopefully not too complicated code...)?

Answer

modulus0 picture modulus0 · Feb 15, 2015

Using realpath from GNU coreutils 8.23 is the simplest, I think:

$ realpath --relative-to="$file1" "$file2"

For example:

$ realpath --relative-to=/usr/bin/nmap /tmp/testing
../../../tmp/testing