1. Overview

Files and directories are building blocks of an operating system. As Linux users, we perform a variety of operations on the files and directories. One such operation is finding a full path of a file. The full path of a file is also known as its absolute or canonical path.

In this tutorial, we’ll discuss various ways to find the full path of a file.

2. Setup

Let’s create files and directories structure to use as an example:

$ cd /tmp
$ mkdir -p dir1/dir2/dir3/dir4/dir5
$ touch dir1/dir2/file2.txt
$ touch dir1/dir2/dir3/dir4/file4.txt
$ touch dir1/dir2/dir3/dir4/dir5/file5.txt

$ tree /tmp/dir1/
/tmp/dir1/
└── dir2
    ├── dir3
    │   └── dir4
    │       ├── dir5
    │       │   └── file5.txt
    │       └── file4.txt
    └── file2.txt

4 directories, 3 files

The readlink command prints canonical file names. We can use the -f option of this command to find the full path of a file:

$ cd /tmp/dir1/dir2/dir3/dir4/dir5/
$ readlink -f file5.txt 
/tmp/dir1/dir2/dir3/dir4/dir5/file5.txt

4. Using the realpath Command

Alternatively, we can use the realpath command to get the absolute path of a file:

$ cd /tmp/dir1/dir2/dir3/dir4/
$ realpath file4.txt 
/tmp/dir1/dir2/dir3/dir4/file4.txt

5. Using the Combination of basename and dirname Commands

The basename command is useful when we want to strip the directory and suffix from filenames. Similarly, we can use the dirname command to strip the last component from the file name:

$ basename /tmp/dir1/dir2/dir3/dir4/file4.txt
file4.txt
$ dirname /tmp/dir1/dir2/dir3/dir4/file4.txt
/tmp/dir1/dir2/dir3/dir4

We can use the combination of these two commands to find the full path of a file. Let’s create a simple shell script for the same:

$ cat get_full_path.sh 
#! /bin/bash
echo "$(cd "$(dirname "$1")" && pwd -P)/$(basename "$1")"

$ chmod +x get_full_path.sh
$ ./get_full_path.sh file4.txt
/tmp/dir1/dir2/dir3/dir4/file4.txt

Firstly, we use the dirname command to find the directory in which a file is located. Then we change the directory using the cd command.

Next, we print the current working directory using the pwd command. Here, we have applied the -P option to show the physical location instead of the symbolic link.

Finally, we use the basename command to print the file name without a directory.

6. Using the find Command

The find command searches for files in a directory hierarchy. We can use this command to print the absolute path of a file:

$ cd /tmp/dir1/
$ find $PWD -type f -name file4.txt 
/tmp/dir1/dir2/dir3/dir4/file4.txt

7. Conclusion

In this article, we discussed various practical examples to find the absolute path of a file. First, we discussed the usage of the readlink and realpath commands. Then, we used a combination of the basename and dirname commands. Finally, we saw the example of the find command. We can use these commands in day-to-day life to boost our productivity.