Re: How to compute the relative path from the absolute paths?(in bash)
From: William (Reply_at_NewsGroup.Please)
Date: Fri, 28 Oct 2005 10:51:08 -0500
"William" <Reply@NewsGroup.Please> wrote in message
> <PengYu.UT@gmail.com> wrote in message
> > 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.):
# Wanted: Relative path from mainPath to target path
set -- $target
for elem in $mainPath
case "$relPath" in
[ "$1" = "$elem" ] || relPath="../$1"
echo "relPath = $relPath"