UNIX Shell: Find Out Real Path Of File or Directory

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 like operating systems? How do I remove references to /./, /../ and extra ‘/’ character in path?

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.

Another option is readlink command to print value of a symbolic link or canonical file name.

Finally, you can use Perl or Python to print value of a symbolic link or canonical file name.

realpath examples

To resolve symbolic link, type:
$ realpath /home
Sample outputs:

/usr/home

To remove characters, run:
$ realpath /etc//apache/.
$ realpath ./foo
$ realpath /../some/where///./../path/

The realpath command included with most Linux distributions and UNIX like 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

Perl program example

Try the following Perl code for portability purpose under various Linux and Unix like oses:

#!/usr/bin/perl
use Cwd 'abs_path';
if (@ARGV != 2 ) {
  print "Usage: $0 --path filen";
  exit;
}
$realfilepath = abs_path("$ARGV[1]");
print "$realfilepathn";

#!/usr/bin/perl
use Cwd ‘abs_path’;
if (@ARGV != 2 ) {
print "Usage: $0 –path filen";
exit;
}
$realfilepath = abs_path("$ARGV[1]");
print "$realfilepathn";

Sample outputs:

Fig.01: Perl program in action

Recommended readings:
  • man pages: readlink and realpath
  • To see Cwd document type: perldoc Cwd

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.