Skip to content

Instantly share code, notes, and snippets.

@biiont
Created October 1, 2015 08:22
Show Gist options
  • Save biiont/543a2f4e9f5136f4f782 to your computer and use it in GitHub Desktop.
Save biiont/543a2f4e9f5136f4f782 to your computer and use it in GitHub Desktop.
Canonical, Absolute and Relative Paths in POSIX Shell
# Prepare
mkdir -p "${HOME}/path without/symlinks"; ln -s "${HOME}/path without" "${HOME}/path with"
TESTPATH="${HOME}/..///${USER}/path with/symlinks///"; echo "${TESTPATH}"
echo "Absolute path: '$(realpath -m ${TESTPATH})'"
echo "Canonical path: '$(realpath -s -m ${TESTPATH})'"
echo "Relative to '/usr/bin': '$(realpath -s -m --relative-to="/usr/bin" ${TESTPATH})'"
echo "Canonical relative to '/usr/bin': '$(realpath -m --relative-to="/usr/bin" ${TESTPATH})'"
echo "Relative with base '/usr/bin': '$(realpath -s -m --relative-base="/usr/bin" ${TESTPATH})'"
echo "Relative with base '${HOME}': '$(realpath -s -m --relative-base="${HOME}" ${TESTPATH})'"
echo "Canonical relative with base '${HOME}': '$(realpath -m --relative-base="${HOME}" ${TESTPATH})'"
echo "Basedir: '$(dirname "$(realpath -s -m ${TESTPATH})")'"
# BASEDIR="$(dirname "$(realpath -s ${0})")"
# Cleanup
rm -rf "${HOME}/path with" "${HOME}/path without"
@HaleTom
Copy link

HaleTom commented Oct 16, 2017

You need "-quotes around $TESTPATH.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment