dirname - Linux
Overview
The dirname
command in Linux extracts the directory path from a given file path. It strips the non-directory suffix from the file name and returns the directory portion. This command is particularly useful in scripting and programming where you need to manipulate file path information dynamically.
Syntax
The basic syntax of the dirname
command is:
dirname [OPTION] NAME...
- NAME…: This parameter is the full file path from which you want to extract the directory portion. You can specify multiple paths.
Options/Flags
dirname
comes with the following options:
-z, --zero
: End each output line with a zero byte (ASCII NUL) instead of a newline. This option is useful when dealing with filenames that contain newlines.--help
: Display a help message and exit.--version
: Output version information and exit.
Examples
Here are some examples of using dirname
:
-
Basic Usage:
Extract the directory path from a full file path:dirname /usr/bin/sort
Output:
/usr/bin
-
Multiple Paths:
Get directory names for multiple paths:dirname /etc/passwd /usr/bin/sort
Output:
/etc /usr/bin
-
Using with Zero Byte Separator:
When handling filenames that might contain newlines:dirname -z /a/b/c/newline_character_file
This outputs
/a/b/c
followed by a NUL character.
Common Issues
- Relative Paths:
Users might expectdirname
to return a dot (.
) for names without slashes. Instead, it returns the path as is:dirname filename
Output:
.
Note: This is actually the expected behavior by POSIX standard.
Integration
dirname
can be integrated with other commands to form powerful command chains:
-
Scripting Example:
A script to copy a file to the same directory as another file:#!/bin/bash file1="/path/to/source/file" file2="/another/path/target" cp "$file1" "$(dirname "$file2")"
-
Combining with
xargs
:
To find the directory names of all.sh
files and process them:find . -name "*.sh" -print | xargs dirname | uniq
Related Commands
basename
: Extracts the filename from a path.cd
: Changes the directory.pwd
: Prints the current directory.
For more information, refer to the dirname(1)
and dirname(3)
man pages, or the GNU Core Utilities documentation online.