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

Summary

printenv - print all or some environment variables

[Source] [Code Walkthrough]

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

Descended from printenv in 3BSD (1979)
Added to Shellutils in November 1992 [First version]
Number of revisions: 92 [Code Evolution]

printenv is a slim, single-purpose utility as opposed to the multifunctional env

Helpers:
  • None
External non-standard helpers:
  • None

Setup

printenv has one important point to consider during setup. Your system's config.h loads system specific headers (including unistd.h). These system headers import your environment string array, environ.

This is array is the primary source of information in the form of name=value

main() initializes the following:

  • ap - Pointer to the variable we want to find
  • env - Pointer to the environment array
  • ep - Pointer to the current environment array
  • i - Generic iterator for argv
  • ok - The return result of the utility
  • optc - The current parsing option
  • opt_nul_terminate_output - Flag indicating null-term end of lines

Parsing

Parsing printenv answers these questions:

  • Are we looking for a specific entry or all entries?
  • Do we null-term or newline each entry?

Parsing failures

The only parsing failure explictly checked is if an unknown option is used.

A parsing failure has a results in an specific error condition in this utility, PRINTENV_FAILURE


Execution

Loop through the entire environment array and:

  • If no target variable was provided, print each entry
  • Match provided variable to the entry and print if matching
  • Print the end of entry character, either \0 or \n

There are no hard failure cases per se, but execution may result in EXIT_FAILURE if there the requested variables aren't matched


[Back to Project Main Page]