location: Pub / Relpath
relpath
- finds the relative path between two paths
1
2
3
4
5 mydir=${0%/}
6 mydir=${0%/*}
7 creadlink="$mydir/creadlink"
8
9 shopt -s extglob
10
11 relpath_ () {
12 path1=$("$creadlink" "$1")
13 path2=$("$creadlink" "$2")
14 orig1=$path1
15 path1=${path1%/}/
16 path2=${path2%/}/
17
18 while :; do
19 if test ! "$path1"; then
20 break
21 fi
22 part1=${path2#$path1}
23 if test "${part1#/}" = "$part1"; then
24 path1=${path1%/*}
25 continue
26 fi
27 if test "${path2#$path1}" = "$path2"; then
28 path1=${path1%/*}
29 continue
30 fi
31 break
32 done
33 part1=$path1
34 path1=${orig1#$part1}
35 depth=${path1//+([^\/])/..}
36 path1=${path2#$path1}
37 path1=${depth}${path2#$part1}
38 path1=${path1##+(\/)}
39 path1=${path1%/}
40 if test ! "$path1"; then
41 path1=.
42 fi
43 printf "$path1"
44
45 }
46
47 relpath_test () {
48 res=$(relpath_ /path1/to/dir1 /path1/to/dir2 )
49 expected='../dir2'
50 test_results "$res" "$expected"
51
52 res=$(relpath_ / /path1/to/dir2 )
53 expected='path1/to/dir2'
54 test_results "$res" "$expected"
55
56 res=$(relpath_ /path1/to/dir2 / )
57 expected='../../..'
58 test_results "$res" "$expected"
59
60 res=$(relpath_ / / )
61 expected='.'
62 test_results "$res" "$expected"
63
64 res=$(relpath_ /path/to/dir2/dir3 /path/to/dir1/dir4/dir4a )
65 expected='../../dir1/dir4/dir4a'
66 test_results "$res" "$expected"
67
68 res=$(relpath_ /path/to/dir1/dir4/dir4a /path/to/dir2/dir3 )
69 expected='../../../dir2/dir3'
70 test_results "$res" "$expected"
71
72
73
74
75 }
76
77 test_results () {
78 if test ! "$1" = "$2"; then
79 printf 'failed!\nresult:\nX%sX\nexpected:\nX%sX\n\n' "$@"
80 fi
81 }
82
83
84
SEO
- find relative path
- determine relative path
- generate relative path
- get relative path
Pub/Relpath (last edited 2011-09-08 12:59:31 by pooryorick)