Re: How to compute the relative path from the absolute paths?(in bash)

From: William (Reply_at_NewsGroup.Please)
Date: 10/28/05


Date: Fri, 28 Oct 2005 10:51:08 -0500


"William" <Reply@NewsGroup.Please> wrote in message
news:vtKdnTin2ahp2P_enZ2dnUVZ_s2dnZ2d@giganews.com...
> <PengYu.UT@gmail.com> wrote in message
> news:1130512627.131217.130650@f14g2000cwb.googlegroups.com...
> > Hi,
> >
> > Suppose I know the absolute paths of two directories? How can I compute
> > the simplest relative path between them?
> >
> > /home/dir1/b
> > /home/dir1/c
> >
> > I want the relative path of b to c is
> > ../b not ../../dir1/b, etc
>
> Just replace all the common path elements with
> a single '..' element. How you do it depends on
> your shell and which tools you want to use.
>
> In bourne shell you could set IFS to '/', then
> use set, shift and a for loop to compare each
> element until you find a difference.
>
> Once you find the difference, you replace
> everything up to that point with ../ and add
> all the leftover elements from your target
> path string.

Here's a sample (could use some input validation,
and you might want to restore IFS, etc.):

#!/bin/sh

# Wanted: Relative path from mainPath to target path
mainPath="/etc/dir1/dir2/dir3/b"
target="/etc/dir1/dir2/dir4/c"
relPath=''
IFS='/'
set -- $target
for elem in $mainPath
do
    case "$relPath" in
        "")
            [ "$1" = "$elem" ] || relPath="../$1"
            ;;
        *)
            relPath="$relPath/$1"
            ;;
    esac
    shift
done

echo "relPath = $relPath"