Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Enable the following for debugging purpose
- # set -vx
- #
- # Resolves any path (even through link-chains etc. to an absolute path.
- #
- # Usage:
- # MY_COMMAND="$(resolvePath "${0}")"
- # MY_DIR="$(dirname "${MY_COMMAND}")"
- #
- function resolvePath() {
- local path="${1}"
- firstTry="$(readlink -f "${path}" 2> /dev/null)"
- if [ -n "${firstTry}" ]; then
- echo "${firstTry}"
- else
- echo "$(_pwdResolvePath "${path}")"
- fi
- }
- #
- # If readlink is not available on the system the fallback is to use
- # pwd -P and the "cd"-approach to resolve a symbolic link.
- #
- function _pwdResolvePath() {
- local path="${1}"
- local cmd dir link
- if [ -d "${path}" ]; then
- cmd=
- dir="${path}"
- else
- cmd="$(basename "${path}")"
- dir="$(dirname "${path}")"
- fi
- cd "$dir"
- if [ ! -d "${path}" ]; then
- while [ -h "$cmd" ]; do
- link="$(ls -l "$cmd" | cut -d\> -f2 | cut -c2-)"
- cmd="$(basename "$link")"
- dir="$(dirname "$link")"
- cd "$dir"
- done
- cmd="/${cmd}"
- fi
- echo "$(pwd -P)${cmd}"
- }
- echo "$(resolvePath "${1}")"
Add Comment
Please, Sign In to add comment