The most reliable method I’ve come across in unix is readlink -f
:
$ readlink -f /x/y/../../a/b/z/../c/d
/a/b/c/d
A couple caveats:
- This also has the side-effect of resolving all symlinks. This may or may not be desirable, but usually is.
readlink
will give a blank result if you reference a non-existant directory. If you want to support non-existant paths, usereadlink -m
instead. Unfortunately this option doesn’t exist on versions of readlink released before ~2005.