Converting relative path into absolute path?

josh picture josh · Oct 28, 2010 · Viewed 50.5k times · Source

I'm not sure if these paths are duplicates. Given the relative path, how do I determine absolute path using a shell script?

Example:

relative path: /x/y/../../a/b/z/../c/d

absolute path: /a/b/c/d

Answer

bukzor picture bukzor · Oct 28, 2010

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:

  1. This also has the side-effect of resolving all symlinks. This may or may not be desirable, but usually is.
  2. readlink will give a blank result if you reference a non-existant directory. If you want to support non-existant paths, use readlink -m instead. Unfortunately this option doesn't exist on versions of readlink released before ~2005.