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.

LinuxshellscriptingpathLow risk
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.conf

02What 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

RiskLow risk
!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

Last verified: 2026-09-17 · Category: Files & Folders