How to get absolute File Path in Linux

get absolute File Path in Linux

Everything is considered a file in Linux. There are regular files, directories, symbolic links, and other types of files. You create a directory to manage files. The multilevel directory structure is common in Linux. You will find a big directory structure like /home/il/my_files/imp/abc.txt. The question here is, how to get an absolute file path in Linux.

That is what we are going to cover in this article.

You can use readlink, realpath, and find commands to get the complete path of the file. This is very useful for scripting and configuration.

Before we begin, let’s create a directory and files.

First, make some folders

mkdir -p ~/dir1/dir2/dir3/dir4/dir5

And now some test files

touch dir1/dir2/dir3/dir4/file4.txt
touch dir1/dir2/dir3/dir4/dir5/file5.txt

The resultant directory structure is as follows:

└── dir2
    └└── dir3
        └── dir4
            ├─── dir5
            │ └└─── file5.txt
            └─── file4.txt

4 directories, 2 files

Method 1: Using the readlink command

The readlink command is a commonly used tool on Linux systems, mainly to find out where the symbolic link points. However, you can also use it to get the absolute path to a file as well.

For example, from dir5 you can run readlink with the -f option

readlink -f file5.txt

Below is the output showing the complete path.

/home/user/dir1/dir2/dir3/dir4/dir5/file5.txt

Method 2: Get the absolute path to a file with realpath

Another easy-to-use command to get a complete file path is realpath. This command prints the resolved absolute file name. It is simple to use, and just run it like realpath <file_name>. In our case

realpath file5.txt

And the output is the same as the previous command.

/home/user/dir1/dir2/dir3/dir4/dir5/file5.txt

Method 3: Using the find command

The find command, as the name implies, allows the user to search for files using the terminal. It is very flexible and even if it is complex to use at first, it becomes a habit.

Use the find command to get the absolute path to a file as shown below

find $PWD -type f -name file4.txt 

Remember, this command does a search, so its execution is slower.

Conclusion

Although, it may seem a bit simple and useless, knowing the absolute path of a file is a trick that you should always know. Especially if you are a programmer or a server administrator. It is also quite useful in bash scripts where you need to automate processes.

I hope this post helped you. Please share it with all your friends.

Share This:

Leave a Comment

Your email address will not be published. Required fields are marked *