How to Calculate a Relative Path from Two Absolute Paths in Linux Shell?
We Have Two Paths. First One Is Directory, Second Either a Directory or a File. /a/B/C and /a/D/E. Txt Relative Path from First Path to Second Will Be: .. /...
We have two paths. First one is directory, second either a directory or a file.
/a/b/c and /a/d/e.txt
Relative path from first path to second will be:
../../d/e.txt
How to calculate that in Linux terminal? For those who ask “What is usage case?” one could use this—for example—to create lots of relative symlinks.
3 Answers
Assuming GNU coreutils:
For symlinks,
lnhas recently learned the--relativeoption.For everything else,
realpathsupports options--relative-to=and--relative-base=.
For me, this answer (which uses a python oneliner) works perfect.
$ python -c "import os.path; print os.path.relpath('/a/d/e.txt', '/a/b/c')"
../../d/e.txt
Tested successfully on linux (Kubuntu 14.04) an on Mac OSX, needs Python 2.6.
To not depend on realpath that is not consistently available and minimize the dependencies, I came up with this (using a little help from this answer):
function relative_path_from_to() {
# strip trailing slashes
path1=${1%\/}
path2=${2%\/}
# common part of both paths
common=$(printf '%s\x0%s' "${path1}" "${path2}" | sed 's/\(.*\/\).*\x0\1.*/\1/')
# how many directories we have to go up to the common part
up=$(grep -o "/" <<< ${path1#$common} | wc -l)
# create a prefix in the form of ../../ ...
prefix=""; for ((i=0; i<=$up; i++)); do prefix="$prefix../"; done
# return prefix plus second path without common
printf "$prefix${2#$common}"
}
Spawns a subshell for finding the common part of both pathes. I hope you like it - works for me.