Friday, June 14, 2024
HomeHow toLinux readlink and realpath Command Tutorial for Beginners (with Examples)

Linux readlink and realpath Command Tutorial for Beginners (with Examples)

We’ve already discussed the ln command, which lets you create links between files. However, some tools allow you to resolve these links.

In this tutorial, we will discuss the basics of realpath and readlink commands that are similar (if not same) in that they display resolved symbolic links in output. But before we do that, it’s worth mentioning that all examples here have been tested on Ubuntu 24.04 LTS and Debian 12.

As mentioned in the beginning, both realpath and readlink commands display the resolved path for symlinks in the output.

Following is their syntax:

realpath [OPTION]... FILE...
readlink [OPTION]... FILE...

And here’s what their respective man pages say:

Print the resolved absolute file name
print resolved symbolic links or canonical file names

Following are some Q&A-styled examples that should give you a better idea on how these tools work.

Simple: just provide the file or path as input. The following example shows both these commands resolving a symbolic link.

And here’s how they work with paths:

So you can see both commands successfully resolved symlinks in the two cases.

Q2. How to print the resolved path relative to a directory?

The realpath command lets you easily do this. For example, suppose this is what you are trying to do:

realpath /var/local/Downloadslink

However, an additional requirement is to have the output of this command relative to the /home/himanshu directory. Then following is the command that you need to execute:

realpath /var/local/Downloadslink --relative-to=/home/himanshu

Here’s the output:


So you can see that the ‘–relative-to’ option allowed you to have output relative to the /home/himanshu directory.

Q3. How to just get rid of .. in paths?

There may be times when expanding/resolving symlinks isn’t the aim, but getting rid of .. in the path is. The realpath command allows you to do this.

All you have to do is to use the -s command line option. Here’s an example:

realpath -s ../../var/local/Downloadslink

And following is the output of this command:


Q4. How to change the delimiting character?

By default, the newline is used as the delimiting character. However, both commands provide a way to have NUL as delimiter instead.

The option you need to use in both cases is -z.

realpath -z [FILE/PATH]
readlink -z [FILE/PATH]


We’ve discussed here just a handful of options/features these commands provide. Once you are done practicing these, head to readlink and realpath man pages (here and here) to learn more about these tools.



Please enter your comment!
Please enter your name here

Most Popular