-
-
Save hercynium/3899407 to your computer and use it in GitHub Desktop.
A Bash script providing a command for computing relative path between two filesystem paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# relpath -- Compute relative path from a given DIR to given PATHs | |
# Usage: relpath DIR PATH... | |
# | |
# Example: relpath /a/b/c /a/d/e/f | |
# prints: ../../d/e/f | |
# | |
# Example: relpath /a/b/c / | |
# prints: ../../../ | |
# | |
# Example: relpath /a/b/c /a/b/c/g/h | |
# prints: g/h | |
# lovingly stolen from https://gist.github.com/1573996 | |
relpath() { | |
local from="$1" to="$2" | |
from=${from//\/\//\/} | |
from=${from%/} | |
IFS=/ | |
dirs=(${from#/}) | |
for to; do | |
to=${to//\/\//\/} | |
to=${to%/} | |
local commonPrefix=/ d= | |
for d in "${dirs[@]}"; do | |
case "$to/" in "$commonPrefix$d/"*) ;; | |
*) break;; | |
esac | |
commonPrefix+="$d/" | |
done | |
local ancestor="${from#${commonPrefix%/}}" | |
ancestor=${ancestor//[^\/]/} | |
ancestor=${ancestor//\//..\/} | |
done | |
echo "$ancestor${to#$commonPrefix}" | |
} | |
relpath "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment