How to resolve symbolic links in a shell script

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

    Here I present what I believe to be a cross-platform (Linux and macOS at least) solution to the answer that is working well for me currently.

    crosspath()
    {
        local ref="$1"
        if [ -x "$(which realpath)" ]; then
            path="$(realpath "$ref")"
        else
            path="$(readlink -f "$ref" 2> /dev/null)"
            if [ $? -gt 0 ]; then
                if [ -x "$(which readlink)" ]; then
                    if [ ! -z "$(readlink "$ref")" ]; then
                        ref="$(readlink "$ref")"
                    fi
                else
                    echo "realpath and readlink not available. The following may not be the final path." 1>&2
                fi
                if [ -d "$ref" ]; then
                    path="$(cd "$ref"; pwd -P)"
                else
                    path="$(cd $(dirname "$ref"); pwd -P)/$(basename "$ref")"
                fi
            fi
        fi
        echo "$path"
    }
    

    Here is a macOS (only?) solution. Possibly better suited to the original question.

    mac_realpath()
    {
        local ref="$1"
        if [[ ! -z "$(readlink "$ref")" ]]; then
            ref="$(readlink "$1")"
        fi
        if [[ -d "$ref" ]]; then
            echo "$(cd "$ref"; pwd -P)"
        else
            echo "$(cd $(dirname "$ref"); pwd -P)/$(basename "$ref")"
        fi
    }
    

提交回复
热议问题