When navigating through complex directories in a Linux terminal, you will frequently encounter symbolic links (symlinks). A symlink acts as a shortcut, pointing to another file or directory located elsewhere on the filesystem. While the ls -l command can show you where a symlink points, it often fails if the link points to a relative path or if you need to capture the target destination inside a bash script. The most reliable tool for tracking down the true, absolute path of a symlink is the readlink command.
How the readlink Command Works
At its most basic, readlink simply reads the metadata of a symbolic link and prints the exact string of text it was programmed to point to.
If you have a symlink named current_log that points to /var/log/apache2/error.log, you can run:
readlink current_log
The terminal will output:
/var/log/apache2/error.log
However, this basic usage has a flaw. If the symlink was created using a relative path (e.g., pointing simply to ../error.log), the basic readlink command will literally output ../error.log, which is often useless if your bash script needs to know the exact, absolute path on the hard drive.
How to Resolve Absolute Paths
To force the utility to calculate the full, absolute path regardless of how the symlink was originally created, you must use the -f (canonicalize) flag.
readlink -f current_log
By using the -f flag, the command will traverse the directory structure, resolve any relative ../ instructions, and output the true, absolute path, such as /var/log/apache2/error.log.
Crucially, the -f flag also works on standard files and directories that are not symlinks. If you pass a regular text file to readlink -f, it will simply output the absolute path to that file, making it an incredibly useful trick for quickly finding your exact location on the filesystem.
Resolving Nested Symlinks
In highly complex systems, you might encounter a symlink that points to another symlink, which points to a third symlink, and so on. If you use the basic readlink command, it will only resolve the very first link in the chain.
The -f flag automatically solves this problem as well. It will recursively follow every single symlink in the chain until it finally reaches the actual, physical file at the very end of the line. Because of this powerful recursive resolution, using readlink -f is considered the standard best practice whenever you need to reliably capture a file path in a Linux automation script.