Skip to content

Instantly share code, notes, and snippets.

@netj
Created January 7, 2012 06:32
Show Gist options
  • Save netj/1573996 to your computer and use it in GitHub Desktop.
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
#!/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