dirname Command

The dirname command is a standard Unix/Linux utility that extracts the directory portion of a pathname. It removes the last slash-delimited component from a string, which is typically a filename or a trailing directory name.

Syntax

dirname [OPTION] NAME...

Description

dirname is useful in shell scripting for manipulating file paths. It takes a pathname as input and prints all but the last component of that pathname. If the pathname contains no slashes, dirname prints a single dot (.) indicating the current directory.

Common uses include:

  • Extracting the directory path from a file's full path
  • Getting the parent directory of a given path
  • Processing lists of file paths

Common Options

Option Description
-z, --zero End each output line with NUL, not newline

Examples

Extract directory from a file path

dirname /home/user/documents/report.txt
# Output: /home/user/documents

This example extracts the directory path from the given file's absolute path.

Extract directory from a directory path

dirname /var/log/apache/
# Output: /var/log

Even with a trailing slash, dirname removes the last component.

Process multiple paths

dirname /etc/passwd /usr/local/bin/script.sh
# Output: # /etc # /usr/local/bin

Processes multiple pathnames and prints each result on a new line.

Path with no slashes

dirname myfile.txt
# Output: .

If the input contains no slashes, it returns a dot, representing the current directory.

See also