Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a shell script that does it without calling other programs:</p> <pre class="lang-sh prettyprint-override"><code>#! /bin/env bash #bash script to find the relative path between two directories mydir=${0%/} mydir=${0%/*} creadlink="$mydir/creadlink" shopt -s extglob relpath_ () { path1=$("$creadlink" "$1") path2=$("$creadlink" "$2") orig1=$path1 path1=${path1%/}/ path2=${path2%/}/ while :; do if test ! "$path1"; then break fi part1=${path2#$path1} if test "${part1#/}" = "$part1"; then path1=${path1%/*} continue fi if test "${path2#$path1}" = "$path2"; then path1=${path1%/*} continue fi break done part1=$path1 path1=${orig1#$part1} depth=${path1//+([^\/])/..} path1=${path2#$path1} path1=${depth}${path2#$part1} path1=${path1##+(\/)} path1=${path1%/} if test ! "$path1"; then path1=. fi printf "$path1" } relpath_test () { res=$(relpath_ /path1/to/dir1 /path1/to/dir2 ) expected='../dir2' test_results "$res" "$expected" res=$(relpath_ / /path1/to/dir2 ) expected='path1/to/dir2' test_results "$res" "$expected" res=$(relpath_ /path1/to/dir2 / ) expected='../../..' test_results "$res" "$expected" res=$(relpath_ / / ) expected='.' test_results "$res" "$expected" res=$(relpath_ /path/to/dir2/dir3 /path/to/dir1/dir4/dir4a ) expected='../../dir1/dir4/dir4a' test_results "$res" "$expected" res=$(relpath_ /path/to/dir1/dir4/dir4a /path/to/dir2/dir3 ) expected='../../../dir2/dir3' test_results "$res" "$expected" #res=$(relpath_ . /path/to/dir2/dir3 ) #expected='../../../dir2/dir3' #test_results "$res" "$expected" } test_results () { if test ! "$1" = "$2"; then printf 'failed!\nresult:\nX%sX\nexpected:\nX%sX\n\n' "$@" fi } #relpath_test </code></pre> <p>source: <a href="http://www.ynform.org/w/Pub/Relpath" rel="nofollow noreferrer">http://www.ynform.org/w/Pub/Relpath</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload