dirname
Command: Extracting Directory Names
Summary
The dirname
command extracts the directory portion of a given file name or path. It's useful for scripts where you need to work with the directory containing a file, rather than the file itself.
Introduction
The dirname
command is a simple but powerful tool in Linux used to strip the last component from a file name. It essentially returns the path to the directory that contains the specified file or directory. This can be incredibly useful in shell scripts for determining where a script is located, manipulating file paths, and managing directories.
Use case and Examples
Extracting the Directory of a File
This command will output/home/user/documents
. It takes the full path to the report.txt
file and returns the directory in which it resides. Extracting the Directory of a Directory
This command will output/usr/local
. It works equally well with directories, returning the parent directory. Using with Relative Paths
This command will typically output.
, representing the current directory. The dirname
command works with relative paths as well. Handling Multiple Arguments
This command will output:dirname
can take multiple arguments, processing each one separately and printing the results on separate lines. Using with Variable Expansion
This demonstrates howdirname
can be used within a script to extract the directory from a variable containing a file path. The script then prints the extracted directory. Commonly used flags
Flag | Description | Example |
---|---|---|
--help | Displays help information and exits. | dirname --help |
--version | Displays version information and exits. | dirname --version |
-z , --zero | Output a zero byte (ASCII NUL) instead of a newline character at the end of each output line. This is useful when piping the output to commands like xargs -0 . | dirname /path/to/file -z | xargs -0 rm -rf |