readlink Command

The readlink command in Linux is used to resolve symbolic links (symlinks) and print the canonicalized absolute pathname of a file or directory. It's a valuable tool for understanding the true location of files, especially in complex file system structures with many links.

Syntax

readlink [OPTION]... FILE

Description

By default, readlink prints the value of a symbolic link. With options, it can provide more comprehensive path resolution, including resolving all components of a path to their canonical form, which means eliminating any ., .., or symbolic link components.

Common uses include:

  • Finding the target of a symbolic link.
  • Getting the absolute, canonical path of a file.
  • Verifying file existence and accessibility through links.
  • Scripting tasks that require absolute file paths.

Common Options

Option Description
-f, --canonicalize Canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist.
-e, --canonicalize-existing Canonicalize by following every symlink in every component of the given name recursively, and all components must exist.
-m, --canonicalize-missing Canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence.
-n, --no-newline Do not output the trailing newline.
-q, --quiet Suppress most error messages.
-v, --verbose Report all error messages.

Examples

Resolve a symbolic link

ln -s /usr/bin/python3 /tmp/python_link
readlink /tmp/python_link
# Output: /usr/bin/python3

Shows the target path of a symbolic link.

Print the canonicalized absolute path

readlink -f ./../my_folder/./file.txt
# Example Output: /home/user/my_folder/file.txt

Resolves all symlinks and ./.. components to give the absolute path.

Resolve a path with non-existent components (using -m)

readlink -m /nonexistent/path/to/file.txt
# Output: /nonexistent/path/to/file.txt

The -m option attempts to canonicalize the path even if some components don't exist.

Check if a file is a symbolic link

if [ -L my_symlink ]; then echo "It's a symlink"; fi

A shell script example to check if a file is a symbolic link before using readlink.

See also