Skip to content

Instantly share code, notes, and snippets.

@hercynium
Forked from netj/relpath
Created October 16, 2012 13:51
Show Gist options
  • Save hercynium/3899407 to your computer and use it in GitHub Desktop.
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
#!/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