Search code examples
unixpath

Converting relative path into absolute path?


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

Solution

  • From http://www.robertpeaslee.com/index.php/converting-a-relative-path-to-an-absolute-path-in-bash/ (now a dead link, unfortunately):

    #!/bin/bash
    
    # Assume parameter passed in is a relative path to a directory.
    # For brevity, we won't do argument type or length checking.
    
    ABS_PATH=`cd "$1"; pwd` # double quotes for paths that contain spaces etc...
    echo "Absolute path: $ABS_PATH"
    

    You can also do a Perl one-liner, e.g. using Cwd::abs_path.