x404.co.uk
http://www.x404.co.uk/forum/

Finding the relative path between two absolute ones
http://www.x404.co.uk/forum/viewtopic.php?f=4&t=8293
Page 1 of 1

Author:  forquare1 [ Sun May 16, 2010 9:26 pm ]
Post subject:  Finding the relative path between two absolute ones

Hi all,

I'm writing a bash script whereby the user passes in two paths and the script tells you the relative path from the first to the last. The only problem is that I've got no idea how to do it...

For example, the relative path between these two absolute ones
/tmp/test
~/Documents
Would be
../../Users/benlavery/Documents

It needs to be relative because I'm using the script to generate paths that will work on a number of machines and different OS's where files will be in different places, but relative to each other.

Thanks for any help,
Ben

Author:  finlay666 [ Sun May 16, 2010 9:35 pm ]
Post subject:  Re: Finding the relative path between two absolute ones

Could you parse each path then starting at root

omit matches

and add the ..\ where needed , best way is probably a singly linked list



... There is probably a better solution though, possibly using the PATH environment variable or similar

Author:  forquare1 [ Sun May 16, 2010 9:45 pm ]
Post subject:  Re: Finding the relative path between two absolute ones

Thanks for the reply Finley,
After some more Googling (thought I'd post up here as half an hour hadn't thrown up anything), I've found a solution:

Code:
#!/bin/bash

# usage: relpath from to

if [[ "$1" == "$2" ]]
then
    echo "."
    exit
fi

IFS="/"

current=($1)
absolute=($2)

abssize=${#absolute[@]}
cursize=${#current[@]}

while [[ ${absolute[$level]} == ${current[$level]} ]]
do
    (( level++ ))
    if (( level > abssize || level > cursize ))
    then
        break
    fi
done

for ((i = level; i < cursize; i++))
do
    if ((i > level))
    then
        newpath=$newpath"/"
    fi
    newpath=$newpath".."
done

for ((i = level; i < abssize; i++))
do
    if [[ -n $newpath ]]
    then
        newpath=$newpath"/"
    fi
    newpath=$newpath${absolute[i]}
done

echo "$newpath"

Author:  finlay666 [ Sun May 16, 2010 11:47 pm ]
Post subject:  Re: Finding the relative path between two absolute ones

forquare1 wrote:
Thanks for the reply Finley,


........

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/