How to resolve symbolic links in a shell script

后端 未结 19 2239
死守一世寂寞
死守一世寂寞 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:39

    Is your path a directory, or might it be a file? If it's a directory, it's simple:

    (cd "$DIR"; pwd -P)
    

    However, if it might be a file, then this won't work:

    DIR=$(cd $(dirname "$FILE"); pwd -P); echo "${DIR}/$(readlink "$FILE")"
    

    because the symlink might resolve into a relative or full path.

    On scripts I need to find the real path, so that I might reference configuration or other scripts installed together with it, I use this:

    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
      DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
      SOURCE="$(readlink "$SOURCE")"
      [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
    done
    

    You could set SOURCE to any file path. Basically, for as long as the path is a symlink, it resolves that symlink. The trick is in the last line of the loop. If the resolved symlink is absolute, it will use that as SOURCE. However, if it is relative, it will prepend the DIR for it, which was resolved into a real location by the simple trick I first described.

提交回复
热议问题