Last active
September 19, 2021 05:59
-
-
Save mawillcockson/fd121cd348d331b31be62ed59c737869 to your computer and use it in GitHub Desktop.
rough equivalent of `realpath -eq` in POSIX Shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Similar to `realpath -eq` | |
realpath() { | |
if [ "$#" -ne 1 ]; then | |
return 1 | |
elif ! OLD_CD="$(pwd -P)" > /dev/null 2>&1 ; then | |
# This depends on `pwd -P` working, and if it's not, we can't proceed anyways | |
return 1 | |
elif [ -z "${1%%/*}" ]; then | |
# Removing everything after the first / leaves nothing, so the path starts with /, and is absolute | |
THE_PATH="$1" | |
else | |
# The path is not absolute, so add the path to the current directory to that path | |
THE_PATH="${OLD_CD}/$1" | |
fi | |
if [ -f "${THE_PATH}" ]; then | |
# It's a file, so remove everything after and including last slash | |
DIR="${THE_PATH%/*}" | |
# Remove everything up to and including the last slash before the file name | |
FILE="${THE_PATH##*/}" | |
elif [ -d "${THE_PATH}" ]; then | |
# It's a directory, so remove trailing slash, if there is one | |
DIR="${THE_PATH%/}" | |
else | |
# It's neither a directory, nor a file, so we can't get the realpath to it | |
return 1 | |
fi | |
if [ -z "${DIR}" ]; then | |
# The path given was at the root of the filesystem (i.e. consisted of one / which was removed earlier) | |
echo "/${FILE:-""}" | |
return 0 | |
fi | |
if ! cd "${DIR}" > /dev/null 2>&1 ; then | |
# Can't cd to the directory, either because it doesn't exist, or we don't have access | |
return 1 | |
fi | |
# If it didn't fail, we've changed directory, and can echo the absolute path to where we are | |
if ! ABSOLUTE_PATH="$(pwd -P)" > /dev/null 2>&1 ; then | |
# Why would it failing now and not before? I don't know, but that's an error | |
return 1 | |
fi | |
# If this was a path to a file... | |
if [ -n "${FILE:-""}" ]; then | |
# ...add the file back to the directory | |
echo "${ABSOLUTE_PATH}/${FILE}" | |
else | |
echo "${ABSOLUTE_PATH}" | |
fi | |
if ! cd "${OLD_CD}" > /dev/null 2>&1 ; then | |
# We can't cd back to the directory we started in, and that's very weird | |
return 1 | |
fi | |
# Unset variables used | |
unset -v OLD_CD > /dev/null 2>&1 || true | |
unset -v THE_PATH > /dev/null 2>&1 || true | |
unset -v FILE > /dev/null 2>&1 || true | |
unset -v DIR > /dev/null 2>&1 || true | |
unset -v ABSOLUTE_PATH > /dev/null 2>&1 || true | |
return 0 | |
} | |
export realpath |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment