@@ -0,0 +1,40 | |||||
|
1 | #!/bin/bash | |||
|
2 | # both $1 and $2 are absolute paths (biginning with /) | |||
|
3 | # returns $2 relative to $1 | |||
|
4 | ||||
|
5 | source=$1 | |||
|
6 | target=$2 | |||
|
7 | ||||
|
8 | common_part=$source # for now | |||
|
9 | result="" # for now | |||
|
10 | ||||
|
11 | while [[ "${target#$common_part}" == "${target}" ]]; do | |||
|
12 | # no match, means that candidate common part is not correct | |||
|
13 | # go up one level (reduce common part) | |||
|
14 | common_part="$(dirname $common_part)" | |||
|
15 | # and record that we went back, with correct / handling | |||
|
16 | if [[ -z $result ]]; then | |||
|
17 | result=".." | |||
|
18 | else | |||
|
19 | result="../$result" | |||
|
20 | fi | |||
|
21 | done | |||
|
22 | ||||
|
23 | if [[ $common_part == "/" ]]; then | |||
|
24 | # special case for root (no common path) | |||
|
25 | result="$result/" | |||
|
26 | fi | |||
|
27 | ||||
|
28 | # since we now have identified the common part, | |||
|
29 | # compute the non-common part | |||
|
30 | forward_part="${target#$common_part}" | |||
|
31 | ||||
|
32 | # and now stick all parts together | |||
|
33 | if [[ -n $result ]] && [[ -n $forward_part ]]; then | |||
|
34 | result="$result$forward_part" | |||
|
35 | elif [[ -n $forward_part ]]; then | |||
|
36 | # extra slash removal | |||
|
37 | result="${forward_part:1}" | |||
|
38 | fi | |||
|
39 | ||||
|
40 | echo $result |
General Comments 0
You need to be logged in to leave comments.
Login now