Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 305
josh Avatar asked Oct 28 '10 16:10

josh


People also ask

How do you convert relative path to absolute path in Python?

Use abspath() to Get the Absolute Path in Python abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

Can an absolute path be a relative path?

An absolute path is a path that describes the location of a file or folder regardless of the current working directory; in fact, it is relative to the root directory.

How do you find the absolute path of a shell?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

How do you create an absolute path in Java?

File getAbsolutePath() method in Java with Examples The getAbsolutePath() method is a part of File class. This function returns the absolute pathname of the given file object. If the pathname of the file object is absolute then it simply returns the path of the current file object.


1 Answers

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.
like image 63
bukzor Avatar answered Oct 17 '22 07:10

bukzor