macos - Bash script absolute path with OSX - Stack Overflow

Ugh. I found the prior answers a bit wanting for a few reasons: in particular, they don't resolve multiple levels of symbolic links, and they are extremely "Bash-y". While the original question does explicitly ask for a "Bash script", it also makes mention of Mac OS X's BSD-like, non-GNU readlink. So here's an attempt at some reasonable portability (I've checked it with bash as 'sh' and dash), resolving an arbitrary number of symbolic links; and it should also work with whitespace in the path(s), although I'm not sure of the behavior if there is white space the base name of the utility itself, so maybe, um, avoid that?

#!/bin/sh
realpath() {
  OURPWD=$PWD
  cd "$(dirname "$1")"
  LINK=$(readlink "$(basename "$1")")
  while [ "$LINK" ]; do
    cd "$(dirname "$LINK")"
    LINK=$(readlink "$(basename "$1")")
  done
  REALPATH="$PWD/$(basename "$1")"
  cd "$OURPWD"
  echo "$REALPATH"
}
realpath "$@"

Hope that can be of some use to someone.


原网址: 访问

创建于: 2018-10-13 15:36:39

目录: default

标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论