Guest User

Untitled

a guest
Jul 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Enable the following for debugging purpose
  4. # set -vx
  5.  
  6. #
  7. # Resolves any path (even through link-chains etc. to an absolute path.
  8. #
  9. # Usage:
  10. # MY_COMMAND="$(resolvePath "${0}")"
  11. # MY_DIR="$(dirname "${MY_COMMAND}")"
  12. #
  13. function resolvePath() {
  14. local path="${1}"
  15.  
  16. firstTry="$(readlink -f "${path}" 2> /dev/null)"
  17. if [ -n "${firstTry}" ]; then
  18. echo "${firstTry}"
  19. else
  20. echo "$(_pwdResolvePath "${path}")"
  21. fi
  22. }
  23.  
  24. #
  25. # If readlink is not available on the system the fallback is to use
  26. # pwd -P and the "cd"-approach to resolve a symbolic link.
  27. #
  28. function _pwdResolvePath() {
  29. local path="${1}"
  30. local cmd dir link
  31.  
  32. if [ -d "${path}" ]; then
  33. cmd=
  34. dir="${path}"
  35. else
  36. cmd="$(basename "${path}")"
  37. dir="$(dirname "${path}")"
  38. fi
  39.  
  40. cd "$dir"
  41.  
  42. if [ ! -d "${path}" ]; then
  43. while [ -h "$cmd" ]; do
  44. link="$(ls -l "$cmd" | cut -d\> -f2 | cut -c2-)"
  45. cmd="$(basename "$link")"
  46. dir="$(dirname "$link")"
  47. cd "$dir"
  48. done
  49. cmd="/${cmd}"
  50. fi
  51.  
  52. echo "$(pwd -P)${cmd}"
  53. }
  54.  
  55. echo "$(resolvePath "${1}")"
Add Comment
Please, Sign In to add comment