absolute-path

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

大兔子大兔子 提交于 2019-11-25 20:29:54
Example: absolute="/foo/bar" current="/foo/baz/foo" # Magic relative="../../bar" How do I create the magic (hopefully not too complicated code...)? modulus0 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 xni $ python -c "import os.path; print os.path.relpath('/foo/bar', '/foo/baz/foo')" gives: ../../bar Offirmo This is a corrected, fully functional improvement of the currently best rated solution from @pini (which sadly handle only a few cases)