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
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
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
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:
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.Take a look at 'realpath'.
$ realpath
usage: realpath [-q] path [...]
$ realpath ../../../../../
/data/home