Friday, May 25, 2012

UNIX Shell: Find Out Real Path Of File ( Directory )

Q. Some of my programs and scripts needs a real path and not a a symbolic link. How to I determine a real path of any directory under Linux / UNIX operating systems? How do I remove references to /./, /../ and extra '/' character in path?

A. To get physical path use realpath command. The realpath command uses the realpath() function to resolve all symbolic links, extra / characters and references to /./ and /../ in path. This is useful for shell scripting and security related applications.

realpath examples

Resolve symbolic link:
$ realpath /home
Sample output:
/usr/home
Remove characters:
$ realpath /etc//apache/.
$ realpath ./foo
$ realpath /../some/where///./../path/

realpath includes with many distro and UNIX operating system such as FreeBSD. To install realpath under Debian / Ubuntu Linux, enter:
$ sudo apt-get install realpath

readlink command

Please note that mostly the same functionality is provided by the -f option of the readlink command:
$ readlink -f /home

No comments:

Post a Comment