dirname — Return the directory components of a path name

Format

dirname pathname

Description

dirname deletes the trailing part of a file name. The result is the path name of the directory that contains the file. This is useful in shell scripts. dirname does not try to validate the path name. For validation, use pathchk.

dirname follows these rules:

  1. If pathname is //, return it.
  2. Otherwise, if it is all slashes, return one slash.
  3. Otherwise, remove all trailing slashes.
  4. If there are no slashes remaining in pathname, return period (.).
  5. Otherwise, remove trailing nonslash characters.
  6. If the remaining string is //, return it.
  7. Otherwise, remove any trailing slashes.
  8. If the resulting string is empty, return period (.).
  9. Otherwise, return the resulting string.

Examples

The command:
dirname src/lib/printf.c
produces:
src/lib

Localization

dirname uses the following localization environment variables:
  • LANG
  • LC_ALL
  • LC_CTYPE
  • LC_MESSAGES
  • NLSPATH

See Localization for more information.

Exit values

0
Successful completion
1
Failed
2
Unknown command-line option

Portability

POSIX.2, X/Open Portability Guide, UNIX systems.

Related information

basename, pathchk