Skip to content

Instantly share code, notes, and snippets.

@brianoflan
Created April 4, 2018 20:30
Show Gist options
  • Save brianoflan/1032a5398c21a882a1352c392de8739a to your computer and use it in GitHub Desktop.
Save brianoflan/1032a5398c21a882a1352c392de8739a to your computer and use it in GitHub Desktop.
Define realpath in a way that works like 'readlink -f ...' even on macOS
_realpath() {
local return=0
local result=''
local arg=${1:-}
[[ $arg ]] || die "ERROR: _realpath: missing operand"
local pwd0=$(pwd)
local base tmp
cd "$arg";
base=$(basename "$(pwd)")
while [[ $base != / ]]; do
if ! cd .. ; then
echo "ERROR: $?: Failed to 'cd ..' from $PWD." 1>&2
return=3
break
fi ;
tmp=$(readlink "$base")
tmp=${tmp:-$base}
tmp=${tmp%/}
if ! cd "$tmp" ; then
echo "ERROR: $?: Failed to 'cd $tmp' from $PWD." 1>&2
return=4
break
fi ;
tmp=$(basename "$PWD")
if ! cd .. ; then
echo "ERROR: $?: Failed to 'cd ..' from $PWD." 1>&2
return=5
break
fi ;
result="$tmp${result:+/}$result"
base=$(basename "$(pwd)")
done ;
result="/$result"
cd "$pwd0" && echo "$result" && return $return
}
die() {
echo "${1:ERROR}"
exit ${2:-2}
}
type realpath >/dev/null 2>&1 || realpath() {
if type grealpath >/dev/null 2>&1 ; then
grealpath "$@"
elif type readlink >/dev/null 2>&1 && readlink -f . >/dev/null 2>&1 ; then
readlink -f "$@"
elif type greadlink >/dev/null 2>&1 && greadlink -f . >/dev/null 2>&1 ; then
greadlink -f "$@"
else
_realpath "$@"
fi ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment