How to resolve symbolic links in a shell script

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

    This is a symlink resolver in Bash that works whether the link is a directory or a non-directory:

    function readlinks {(
      set -o errexit -o nounset
      declare n=0 limit=1024 link="$1"
    
      # If it's a directory, just skip all this.
      if cd "$link" 2>/dev/null
      then
        pwd -P
        return 0
      fi
    
      # Resolve until we are out of links (or recurse too deep).
      while [[ -L $link ]] && [[ $n -lt $limit ]]
      do
        cd "$(dirname -- "$link")"
        n=$((n + 1))
        link="$(readlink -- "${link##*/}")"
      done
      cd "$(dirname -- "$link")"
    
      if [[ $n -ge $limit ]]
      then
        echo "Recursion limit ($limit) exceeded." >&2
        return 2
      fi
    
      printf '%s/%s\n' "$(pwd -P)" "${link##*/}"
    )}
    

    Note that all the cd and set stuff takes place in a subshell.

提交回复
热议问题