views:

56

answers:

3

Not sure if its a duplicate. 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
+3  A: 

From http://www.robertpeaslee.com/index.php/converting-a-relative-path-to-an-absolute-path-in-bash/:

#!/bin/bash
# Assume parameter passed in is a relative path to a directory.
# For brevity, we won't do argument type or length checking.
echo "Absolute path: `cd $1; pwd`"

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

DVK
Very nice. And what if file name is also given. like /x/y/../../a/b/z/../c/d.txt => /a/b/c/d.txt
Prabhu Jayaraman
Updated with Perl solution which works for files
DVK
+3  A: 

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 run across this, use readlink -m instead. Unfortunately this option doesn't exist on versions of readlink released before ~2005.
bukzor
+1  A: 

Take a look at 'realpath'.

$ realpath

usage: realpath [-q] path [...]

$ realpath ../../../../../

/data/home

SteveMc