Linux readlink and realpath Command Tutorial for Beginners (with Examples)
We’ve already discussed the ln command, which lets you create links between files. But there are also tools that 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 the sense 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 18.04 LTS.
Linux realpath and readlink commands
As already mentioned in the beginning, both realpath and readlink commands display 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.
Q1. How to resolve path using realpath and readlink?
Simple, just provide the file or path as input. 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 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:
Downloads
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:
/var/local/Downloadslink
Q4. How to change the delimiting character?
By default, newline is used as the delimiting character. However, both commands provide 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]
Conclusion
What we’ve discussed here are 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.