relative_path.sh 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #! /bin/sh
  2. # This script computes a relative pathname from $1 to $2
  3. # They are assumed to not contain . or .. pathname components,
  4. # but if both directories exist and cd/pwd canonicalizes pathnames,
  5. # this shouldn't matter. PWD_CMD may be set to some pwd command that does.
  6. # Copyright 2003 Alexandre Oliva <aoliva@redhat.com>
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. # This program is distributed in the hope that it will be useful, but
  12. # WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # General Public License for more details.
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software Foundation, Inc.,
  17. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. from=`(cd $1 > /dev/null && ${PWD_CMD-pwd} || echo $1) 2>/dev/null | sed 's,//*,/,g;s,/*$,,'`
  19. target=`(cd $2 > /dev/null && ${PWD_CMD-pwd} || echo $2) 2>/dev/null | sed 's,//*,/,g;s,/*$,,'`
  20. case $from in /* | "") ;; *) from=`${PWD_CMD-pwd}`/$from ;; esac
  21. case $target in /* | "") ;; *) target=`${PWD_CMD-pwd}`/$target ;; esac
  22. case $target in
  23. "$from" | "$from/"*)
  24. dots=`echo $from | sed s,.,.,g`
  25. echo $target | sed "s,^$dots/*,,;s,[^/]$,&/,"
  26. exit 0
  27. ;;
  28. esac
  29. case $from in
  30. "$target/"*)
  31. dots=`echo $target | sed s,.,.,g`
  32. echo $from/ | sed "s,^$dots/*,,;s,[^/]$,&/,;s,[^/]*/*,../,g;s,[^/]$,&/,"
  33. exit 0
  34. ;;
  35. esac
  36. prefix=`echo $from///$target | sed 's,\(\(/[^/]*\)*\).*///\1.*,\1,'`
  37. dots=`echo $prefix | sed s,.,.,g`
  38. from=`echo $from | sed "s,^$dots,,"`
  39. target=`echo $target | sed "s,^$dots,,"`
  40. from=`echo $from | sed 's,[^/][^/]*,..,g;s,.$,&/,'`
  41. echo ${from}$target/
  42. exit 0