relative_path.sh 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #! /bin/sh
  2. #
  3. # Copyright 2003 Alexandre Oliva <aoliva@redhat.com>
  4. # Copyright (C) 2000-2005 Erik Andersen <andersen@uclibc.org>
  5. #
  6. # Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  7. #
  8. # This script computes a relative pathname from $1 to $2
  9. # They are assumed to not contain . or .. pathname components,
  10. # but if both directories exist and cd/pwd canonicalizes pathnames,
  11. # this shouldn't matter. PWD_CMD may be set to some pwd command that does.
  12. from=`(cd $1 > /dev/null && ${PWD_CMD-pwd} || echo $1) 2>/dev/null | sed 's,//*,/,g;s,/*$,,'`
  13. target=`(cd $2 > /dev/null && ${PWD_CMD-pwd} || echo $2) 2>/dev/null | sed 's,//*,/,g;s,/*$,,'`
  14. case $from in /* | "") ;; *) from=`${PWD_CMD-pwd}`/$from ;; esac
  15. case $target in /* | "") ;; *) target=`${PWD_CMD-pwd}`/$target ;; esac
  16. case $target in
  17. "$from" | "$from/"*)
  18. dots=`echo $from | sed s,.,.,g`
  19. echo $target | sed "s,^$dots/*,,;s,[^/]$,&/,"
  20. exit 0
  21. ;;
  22. esac
  23. case $from in
  24. "$target/"*)
  25. dots=`echo $target | sed s,.,.,g`
  26. echo $from/ | sed "s,^$dots/*,,;s,[^/]$,&/,;s,[^/]*/*,../,g;s,[^/]$,&/,"
  27. exit 0
  28. ;;
  29. esac
  30. prefix=`echo $from///$target | sed 's,\(\(/[^/]*\)*\).*///\1.*,\1,'`
  31. dots=`echo $prefix | sed s,.,.,g`
  32. from=`echo $from | sed "s,^$dots,,"`
  33. target=`echo $target | sed "s,^$dots,,"`
  34. from=`echo $from | sed 's,[^/][^/]*,..,g;s,.$,&/,'`
  35. echo ${from}$target/
  36. exit 0