Use cases of readlink -f vs. readlink -e

I have used readlink -f and readlink -e on multiple occasions to resolve symlinks and as far as I can recall, they give the same results. The man page for readlink from man readlink says:

-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, all components must exist

After reading the man page, although I understand the technical differences between the -f and -e options, I can't think of specific situations where I would use either option. Are there specific use cases and circumstances where one may prefer to use readlink -f to readlink -e and vice versa?


Solution 1:

First of all, both will canonicalize file names that includes:

  • Converting all relative paths to absolute paths

  • Converting all symbolic links to actual hardlinked paths on the filesystem hierarchy

The main differences are:

  • -f will canonicalize a path that may contain a non-existent filesystem portion only at last e.g. a directory or a file, non-zero exit status otherwise; on the other hand, -e will only work only if all components exist in the filesystem, non-zero exit status otherwise

  • Any trailing / is ignored in -f, -e treats trailing / as a directory


So, practically:

  • Use -e when you want to make sure of any path must exist e.g. you need the exit status to do any further logical operation, a if-else test precisely

  • Use -f when you do not want the path to exist strictly now, but you need the full path later e.g. you want to create the resolved file afterwards when a process is running or a filesystem is mounted and so on.

  • Use -e with a trailing / to check for a directory entry explicitly as -f ignores trailing /