Skip to content

Instantly share code, notes, and snippets.

@Uplink03
Last active February 14, 2024 04:54
Show Gist options
  • Save Uplink03/1ac44f13e713ffaa7fde96d40e7874b4 to your computer and use it in GitHub Desktop.
Save Uplink03/1ac44f13e713ffaa7fde96d40e7874b4 to your computer and use it in GitHub Desktop.
Function to get relative path give two absolute paths: a base and a target
#!/bin/zsh
## This function exists because on a Mac the `realpath` program doesn't have a `--relative-to` option like GNU does.
## This file can both be used as a standalone command and as a sourced file to use in other scripts.
relativepath()
{
local RelativeTo=$1 Path=$2
if [[ $RelativeTo != /* || $Path != /* ]]; then
return 1
fi
local -a RelativeToComponents=(${(@s:/:)RelativeTo})
local -a PathComponents=(${(@s:/:)Path})
while [[ ${#RelativeToComponents} -gt 0 && ${#PathComponents} -gt 0 ]]; do
if [[ $RelativeToComponents[1] != $PathComponents[1] ]]; then
break
fi
shift RelativeToComponents
shift PathComponents
done
RelativeToComponents=(${RelativeToComponents//*/..})
local Result=${(j:/:)${RelativeToComponents:-.}}/${(j:/:)PathComponents}
echo $Result
}
if [[ $zsh_eval_context[-1] == toplevel ]]; then
relativepath $@
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment