dirname
Extract directory path from a filename
TLDR
Calculate the parent directory of a given path
Calculate the parent directory of multiple paths
Delimit output with a NUL character instead of a newline (useful when combining with xargs)
SYNOPSIS
dirname [OPTION] NAME...
PARAMETERS
--help
display this help and exit
--version
output version information and exit
DESCRIPTION
The dirname command is a utility in Unix-like systems that strips the last component from a given pathname, outputting the directory portion. For absolute paths like /usr/bin/ls, it returns /usr/bin. For relative paths such as dir/file.txt, it outputs dir. If the path has no slashes (e.g., just a filename), it returns . (current directory).
It processes multiple arguments, printing one line per input. Trailing slashes are ignored, treating /usr/bin//ls as /usr/bin. This makes it ideal for scripting, such as constructing paths dynamically or navigating file hierarchies without parsing manually.
Common uses include generating parent directories in shell scripts, preparing arguments for cd, or feeding into other tools like find. It's lightweight, efficient, and part of coreutils, ensuring portability across Linux distributions.
CAVEATS
Outputs . for paths without slashes. Ignores multiple consecutive slashes. Non-existent paths are handled as strings only.
EXAMPLES
dirname /home/user/doc.txt → /home/user
dirname file → .
dirname /usr/bin/ → /usr/bin
dirname / → /
HISTORY
Introduced in early Unix (1970s AT&T), now standardized in POSIX and maintained in GNU coreutils since 1990s. Widely used in scripts for decades.


