Created
January 7, 2012 06:32
-
-
Save netj/1573996 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 | |
relpath() { | |
local from=$1; shift | |
from=${from//\/\//\/} | |
from=${from%/} | |
IFS=/ dirs=(${from#/}) | |
local to= | |
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//\//..\/} | |
echo "$ancestor${to#$commonPrefix}" | |
done | |
} | |
relpath "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment