diff --git a/realpath.sh b/realpath.sh index 3e8327a..3f2df82 100755 --- a/realpath.sh +++ b/realpath.sh @@ -1,11 +1,39 @@ #!/bin/sh p="${1%/}" -target=$(readlink "$p") +p="${p#/}" -case "$target" in -/*) p="$target";; -'') ;; -*) p="${p%/*}/$target";; -esac +r="" -printf "%s\n" "$p"|sed -e 's@/[^/]*/\.\.\(/\|$\)@/@g' -e 's|/\.\(/\|$\)|/|g' -e 's|/$||g' -e '/^$/d' +while [ -n "$p" ]; do + case "$p" in + */*) + seg="${p%%/*}" + p="${p#*/}" + ;; + *) + seg="$p" + p="" + ;; + esac + case "$seg" in + .) + r="${r%/*}" + continue + ;; + ..) + r="${r%/*/*}" + continue + ;; + esac + r="$r/$seg" + target="$(readlink "$r")" + case "$target" in + /*) p="${target}" + r="";; + '') ;; + *) p="${p%/*}/${target}";; + esac + p="${p#/}" +done + +echo "$r"