Skip to content

Instantly share code, notes, and snippets.

@cokert
Created January 16, 2020 20:47
Show Gist options
  • Save cokert/089100625c6ebed2d10650b223cb7ca4 to your computer and use it in GitHub Desktop.
Save cokert/089100625c6ebed2d10650b223cb7ca4 to your computer and use it in GitHub Desktop.
Relative Paths
# https://stackoverflow.com/a/12498485/88066
# both $1 and $2 are absolute paths beginning with /
# returns relative path to $2/$target from $1/$source
source=$1
target=$2
common_part=$source # for now
result="" # for now
while [[ "${target#$common_part}" == "${target}" ]]; do
# no match, means that candidate common part is not correct
# go up one level (reduce common part)
common_part="$(dirname $common_part)"
# and record that we went back, with correct / handling
if [[ -z $result ]]; then
result=".."
else
result="../$result"
fi
done
if [[ $common_part == "/" ]]; then
# special case for root (no common path)
result="$result/"
fi
# since we now have identified the common part,
# compute the non-common part
forward_part="${target#$common_part}"
# and now stick all parts together
if [[ -n $result ]] && [[ -n $forward_part ]]; then
result="$result$forward_part"
elif [[ -n $forward_part ]]; then
# extra slash removal
result="${forward_part:1}"
fi
echo $result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment