basename and dirname: split a path into name and directory
Use basename (with optional suffix) and dirname in Linux shell scripts to pull apart file paths.
Use basename PATH [SUFFIX] to get the final filename without the suffix, and dirname PATH to get the parent directory.
01Command
Command
$ basename /var/log/syslog .log && dirname /etc/nginx/sites/default.conf02What it does
These two tiny utilities are the portable way to decompose paths in scripts: basename strips everything up to the last slash (and a trailing suffix like .log), dirname strips the last component. Their ${var%/*} and ${var##*/} parameter-expansion equivalents avoid spawning processes, but basename/dirname handle corner cases like paths without slashes and are available on every POSIX system.
03Risk
!Warning: basename removes the suffix only if it matches exactly; it does not verify the extension is real.
04Undo
✓No undo needed — this command does not change persistent state.
05Sources
- dirname(1P) — POSIX manual pageEvidence: dirname returns the string left after deleting the last component and trailing slashes
- basename(1P) — POSIX manual pageEvidence: basename returns the non-directory portion of a pathname; an optional suffix is removed
Last verified: 2026-09-17 · Category: Files & Folders