basename(1)

basename1

Return filename or directory portion of pathname

Usage

basename string [suffix]

basename [-a] [-s suffix] string []

dirname string []

Overview

The basename utility deletes any prefix ending with the last slash ‘/’ character present in string (after first stripping trailing slashes), and a suffix, if given. The suffix is not stripped if it is identical to the remaining characters in string. The resulting filename is written to the standard output. A non-existent suffix is ignored. If -a is specified, then every argument is treated as a string as if basename were invoked with just one argument. If -s is specified, then the suffix is taken as its argument, and all other arguments are treated as a string.

The dirname utility deletes the filename portion, beginning with the last slash ‘/’ character to the end of string (after first stripping trailing slashes), and writes the result to the standard output.

Exit status

The basename and dirname utilities exit 0 on success, and >0 if an error occurs.

Examples

The following line sets the shell variable FOO to /usr/bin.

FOO=`dirname /usr/bin/trail`

Releases

87 releases since FreeBSD 2.0.5-RELEASE; the text changed 46 times.

  1. 2.0.5–2.1.7.1
  2. 2.2.2–2.2.6
  3. 2.2.7–2.2.8
  4. 2.2.9
  5. 3.0–3.2
  6. 3.3–3.5.1
  7. 4.0
  8. 4.1–4.2
  9. 4.3
  10. 4.4–4.6.2
  11. 4.7–4.11
  12. 5.0–5.2.1
  13. 5.3–5.5
  14. 6.0–6.3
  15. 6.4
  16. 7.0
  17. 7.1
  18. 7.2
  19. 7.3
  20. 7.4
  21. 8.0
  22. 8.1
  23. 8.2
  24. 8.3
  25. 8.4
  26. 9.0
  27. 9.1
  28. 9.2
  29. 9.3
  30. 10.0
  31. 10.1
  32. 10.2
  33. 10.3
  34. 10.4
  35. 11.0
  36. 11.1
  37. 11.2
  38. 11.3
  39. 11.4
  40. 12.0
  41. 12.1
  42. 12.2
  43. 12.3
  44. 12.4
  45. 13.0–13.2
  46. 13.3–14.5
  47. 15.0–16.0

Standards

The basename and dirname utilities are expected to be IEEE Std 1003.2 (“POSIX.2”) compatible.

History

The basename utility first appeared in Version 7 AT&T UNIX. The dirname utility first appeared in AT&T System III UNIX.

From base 16.0-CURRENT-20261027-61c70dc16a79 in FreeBSD 16.0-CURRENT (2026-10-27). Parsed by carta from the page's mdoc source.