7

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?

8

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 /

  • Also for you macos guys reading ubuntu forums, readlink didnt get those flags until GPLv3 so they are not present on the macos distro. You can use greadlink if you homebrew modern gnu toolset. – shadowbq Jan 31 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.