dirname — Extract the directory part of a path
Linux / File and disk management / dirname.html
Prints the directory portion of a path by removing its last component.
Basic Information
| Command Name | dirname |
|---|---|
| One-line Introduction | Prints the directory portion of a path by removing its last component. |
| Provided by | GNU coreutils (installed by default on all Linux distributions) |
| Official Documentation | https://man7.org/linux/man-pages/man1/dirname.1.html |
| Supported Operating Systems | Linux, macOS, BSD, WSL |
| Installation Status | Installed by default (no separate installation needed) |
| Category | Linux file and disk management (tags: path, string, script) |
What is this command?
dirname manipulates a path string by removing its last component. It does not check whether the path exists.
Scripts commonly pair it with basename to locate other files relative to their own location.
What problems does it solve?
- A script builds paths relative to its own location
- You only need the parent directory of a file
- You are splitting paths for other commands
- You need pure string handling without resolving links
Key features
Split a path
Prints the path without its last component.
- When to use: You need the directory of a config path
- What you get: The parent directory string
- Limitations: It does not verify that the directory exists.
Locate the script
Combine it with $0 to find the script directory.
- When to use: The script needs sibling files
- What you get: A path relative to the script
- Limitations: Running through a symlink yields the link location.
Handle multiple arguments
Multiple arguments produce one line each.
- When to use: You process several paths at once
- What you get: A result per path
- Limitations: Output order follows the input order.
Installation and usage
Check whether it is installed
dirname --version
sudo apt install coreutils # Debian/Ubuntu sudo dnf install coreutils # Fedora
Real-world examples
Split a path
Get only the directory part of a file path.
dirname /var/log/nginx/access.log
Script directory
Change into the directory that holds the script.
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
cd "$SCRIPT_DIR"
Several paths
Process two paths independently.
dirname /etc/hosts /var/log/syslog