Decoded: readlink (coreutils)

[Back to Project Main Page]

Note: This page explores the design of command-line utilities. It is not a user guide.
[GNU Manual] [No POSIX requirement] [Linux man] [FreeBSD man]

Logical flow of readlink command (coreutils)

Summary

readlink - print value of a symlink or canonical file name

[Source] [Code Walkthrough]

Lines of code: 183
Principal syscall: readlink()
Support syscalls: None
Options: 18 (8 short, 10 long)

Added to Coreutils in January 2003 [First version]
Number of revisions: 93 [Code Evolution]

For most purposes, GNU recommends using the realpath utility in place of readlink

Helpers:
  • None
External non-standard helpers:
  • areadlink_with_size() - Performs the 'readlink' mode execution (from gnulib)
  • canonicalize_filename_mode() - Performs the 'canonicalize' mode execution (from gnulib)
  • error() - Outputs error message to standard error with possible process termination

Setup

readlink initializes local variables in main(), including:

  • can_mode - Flag for canonical mode (default no)
  • status - Return status of the utility
  • optc - The next option to process
  • use_nuls - Flag for the newline output (\n or \0)

Parsing

Parsing readlink considers three questions:

  • Are we in readlink or canonical mode?
  • How should we separate output lines?
  • How much error feedback should we provide the user?

Parsing failures

These failure cases are explicitly checked:

  • No target specified
  • No newline separate with multiple output files (warning)

This failure result in a short error message followed by the usage instructions.


Execution

readlink hands off virtually all the 'work' to gnulib.

After parsing, we know if we're in readlink or canonical mode. We call either areadlink_with_size() or canonicalize_filename_mode() depending on the respective mode.

Then we simply output the results of the function and the desired newline separator.

Execution may fail if either of the gnulib functions fails. Actual error output depends on the verbosity selected by the user


[Back to Project Main Page]