Decoded: echo (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 echo command (coreutils)

Summary

echo - print a line of text

[Source] [Code Walkthrough]

Lines of code: 273
Principal syscall: write() via putchar(), and fputs().
Support syscalls: None
Options: 5

Descended from echo in Version 2 UNIX (1972). Also in CTSS 2ed. (1969)
Added to Shellutils in November 1992 [First version]
Number of revisions: 102 [Code Evolution]

Although echo is still officially supported, POSIX recommends using the printf utility for all future applications

Helpers:
  • hextobin() - Convert hexadecimal to decimal (despite the name)

Setup

The echo utility has little setup. After main() begins, the following flags are defined to assist in flow control:

  • allow_options - Flag to manage options handler
  • display_return - Flag controlling newline output
  • do_v9 - Flag for handing backslash escape characters

Parsing

echo is one of the few coreutils that directly parses input rather than relying on Getopt.

Other than help and version information, we need to check for:

  • How do we handle new lines?
  • How do we handle backslash escape sequences?

There are no parsing failures checked


Execution

The echo utility executes through one long main() procedure and no references to external functions beyond the standard library.

There are two approaches to echoing output:

If not displaying escaped characters:

  • Read in a token (argument/word from the command line)
  • Put that word as-is to STDOUT
  • Decrement token count and increment argv to next token
  • Repeat until no tokens remain from the command line

If displaying escaped characters:

  • Read in a single character from the current argument (argv)
  • If the character is a backslash, output the appropriate escaped character
  • Otherwise, output the regular character as-is
  • Repeat until the end of the argument, then increment to the next argv
  • Repeat until all command line arguments are processed

No execution failure cases explicitly checked


[Back to Project Main Page]