How to resolve symbolic links in a shell script

后端 未结 19 2237
死守一世寂寞
死守一世寂寞 2020-11-28 00:48

Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for

19条回答
  •  情话喂你
    2020-11-28 01:42

    Common shell scripts often have to find their "home" directory even if they are invoked as a symlink. The script thus have to find their "real" position from just $0.

    cat `mvn`
    

    on my system prints a script containing the following, which should be a good hint at what you need.

    if [ -z "$M2_HOME" ] ; then
      ## resolve links - $0 may be a link to maven's home
      PRG="$0"
    
      # need this for relative symlinks
      while [ -h "$PRG" ] ; do
        ls=`ls -ld "$PRG"`
        link=`expr "$ls" : '.*-> \(.*\)$'`
        if expr "$link" : '/.*' > /dev/null; then
          PRG="$link"
        else
          PRG="`dirname "$PRG"`/$link"
        fi
      done
    
      saveddir=`pwd`
    
      M2_HOME=`dirname "$PRG"`/..
    
      # make it fully qualified
      M2_HOME=`cd "$M2_HOME" && pwd`
    

提交回复
热议问题