github.com/opencontainers/umoci@v0.4.8-0.20240508124516-656e4836fb0d/hack/readlinkf.sh (about)

     1  #!/bin/bash
     2  # readlinkf: POSIX-compliant implementation of readlink -f.
     3  # Author: Koichi Nakashima <koichi@nksm.name>
     4  # Licensed under the Creative Commons Zero v1.0 Universal license.
     5  #   <https://creativecommons.org/publicdomain/zero/1.0/>
     6  
     7  # Copied verbatim from v1.1.0 of <https://github.com/ko1nksm/readlinkf>.
     8  
     9  # POSIX compliant version
    10  readlinkf_posix() {
    11    [ "${1:-}" ] || return 1
    12    max_symlinks=40
    13    CDPATH='' # to avoid changing to an unexpected directory
    14  
    15    target=$1
    16    [ -e "${target%/}" ] || target=${1%"${1##*[!/]}"} # trim trailing slashes
    17    [ -d "${target:-/}" ] && target="$target/"
    18  
    19    cd -P . 2>/dev/null || return 1
    20    while [ "$max_symlinks" -ge 0 ] && max_symlinks=$((max_symlinks - 1)); do
    21      if [ ! "$target" = "${target%/*}" ]; then
    22        case $target in
    23          /*) cd -P "${target%/*}/" 2>/dev/null || break ;;
    24          *) cd -P "./${target%/*}" 2>/dev/null || break ;;
    25        esac
    26        target=${target##*/}
    27      fi
    28  
    29      if [ ! -L "$target" ]; then
    30        target="${PWD%/}${target:+/}${target}"
    31        printf '%s\n' "${target:-/}"
    32        return 0
    33      fi
    34  
    35      # `ls -dl` format: "%s %u %s %s %u %s %s -> %s\n",
    36      #   <file mode>, <number of links>, <owner name>, <group name>,
    37      #   <size>, <date and time>, <pathname of link>, <contents of link>
    38      # https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html
    39      link=$(ls -dl -- "$target" 2>/dev/null) || break
    40      target=${link#*" $target -> "}
    41    done
    42    return 1
    43  }