In this article, we cover readlink command-line utility in Linux. It is used to get symbolic link paths in Linux. A symbolic link contains the pathname to the pointed file. And, there are times when symbolic link points to a file or directory that doesn’t exist.
Generally, we use the ls command to know the location where our symbolic link points. But, in certain cases, we do get missing/nested symbolic links. When that happens, while using the ls command, we have to consider each of the symbolic links to get to the source file or directory.
For sure, that isn’t the right way to get things done. That is where readlink command-line utility comes to the rescue.
Before we start, it is better to create two symbolic links i.e. /dev/shm/symlink1 and /dev/shm/symlink2. symlink2 points to symlink1, which then points to /home/$USER/Documents/test/ directory.
mkdir -p /home/$USER/Documents/test/ ln -s /home/$USER/Documents/test/ /dev/shm/symlink1 ln -s /dev/shm/symlink1 /dev/shm/symlink2
where $USER is your system’s username.
readlink: get symbolic links path in Linux
Now, if we do:
ls -l /dev/shm/symlink2
It comes up with the path location:
Not something we want. With the readlink command-line utility, we can get the exact path:
readlink -f /dev/shm/symlink2
where, the -f option follows every symbolic link and gets us the desired outcome.
But, what if the source file or directory is missing? And, using the option -f still points to the source. In cases, the source is missing then use the -e option.
readlink -e /dev/shm/symlink2
It would get the outcome only if the source file exists. Otherwise, nothing would be displayed.
Lastly, the output we receive has the trailing delimiter or there is a new line. If we don’t wish to have that, then use the -n option. For instance,
readlink -nf /dev/shm/symlink2
readlink -ne /dev/shm/symlink2
In conclusion, we have covered here how to use readlink in Linux. The command-line utility helps us get the entry stored for the symbolic link. With the options, readlink would just display the next symbolic link. It won’t look for the nested ones.