readlink
Command in Linux
Summary
The readlink
command displays the target of a symbolic link. It's useful for determining the actual file or directory that a symbolic link points to.
Introduction
The readlink
command is a simple yet powerful tool for working with symbolic links in Linux. Symbolic links, also known as soft links, are pointers to other files or directories. readlink
allows you to resolve these links and find out where they lead. This is particularly useful when dealing with complex directory structures or when you need to understand the underlying file system organization.
Use case and Examples
Following Multiple Levels of Symbolic Links
Ifmy_link
points to another symbolic link, the -f
flag will recursively resolve all links until it reaches the actual file or directory. This will print the absolute path. Checking if a file is a Symbolic Link
if [ -L my_link ]; then
echo "my_link is a symbolic link"
else
echo "my_link is not a symbolic link"
fi
-L
test operator to check if my_link
is a symbolic link before attempting to resolve it. Using readlink
with xargs
to process multiple links
-print0
and xargs -0
handle filenames with spaces correctly. Commonly used flags
Flag | Description | Example |
---|---|---|
-f , --canonicalize | Canonicalize by following every symbolic link in every component of the resulting name. | readlink -f my_link Resolve my_link to its ultimate target, even if it involves multiple links. |
-e , --canonicalize-existing | Canonicalize by following every symlink in every component of the resulting name, but only if the target exists. | readlink -e my_link Resolve my_link only if its target exists. |
-n , --no-newline | Do not output the trailing newline. | readlink -n my_link Print the target without a newline character at the end. |
-v , --verbose | Report errors. | readlink -v non_existing_link Will give an error message if non_existing_link does not exist. |
-z , --zero | End each output line with NUL, not newline. | readlink -z my_link Useful for processing with xargs -0 . |