Decoded: dirname (coreutils)

[Back to Project Main Page]

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

Logical flow of dirname command (coreutils)

Summary

dirname - strip the last file name component

[Source] [Code Walkthrough]

Lines of code: 137
Principal syscall: fwrite()
Support syscalls: None
Options: 4 (1 short, 3 long)

Added to Shellutils in November 1992 [First version]
Number of revisions: 103 [Code Evolution]

Helpers:
  • None
External non-standard helpers:
  • dir_len() - Returns the length of the directory portion of the path
  • error() - Outputs error message to standard error with possible process termination

Setup

dirname prepares one long option (for NUL newlines). main() defines local variables including:

  • dot - A pointer to the dot character
  • use_nuls - Flag for the zero option
  • result - The file result (a path) to be printed
  • len - The length of the result

Parsing

Parsing for dirname only checks if the user requested a NUL termed output. This is useful when the output is piped to another program rather than the terminal.

Parsing failures

Parsing could fail if the user doesn't specify at least one target to resolve the path.


Execution

Presumably the user passed a path to the target. Thus execution does this for each input target:

  • Get the complete target
  • Find the length (position) of the end of the directory name
  • Write the string up to the discovered length to output
  • Output the requested end of line character (\0 or \n)

In the case when no path is provided, just the file name. The result is '.' with length 1

dirname() should not fail during the execution stage


[Back to Project Main Page]