dirname
Overview
dirname removes the last path component, returning the directory portion of a path. Together with basename it covers most shell path-splitting needs: locating a script’s directory, ensuring parent dirs exist, and computing sibling paths.
Syntax
dirname [OPTION] NAME...Common Options
| Option | Description |
|---|---|
-z, --zero |
NUL-terminated output |
GNU coreutils accepts multiple NAME arguments and prints one line each.
Key Use Cases
- Find a script’s directory
mkdir -pparents before writing a file- Compute sibling paths
- Normalize path structure in scripts
- Logging / display of parent locations
Examples with Explanations
Basics
dirname /path/to/file.txt
# /path/to
dirname file.txt
# .
dirname /usr/local/bin/
# /usr/local
dirname /usr
# /
dirname /
# /Multiple arguments
dirname /a/b /c/d/eScript directory pattern
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
# better when $0 is a symlink:
SCRIPT_DIR=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
cd "$SCRIPT_DIR"Ensure parent exists
out=/var/lib/myapp/data/file.db
mkdir -p "$(dirname "$out")"
touch "$out"Sibling paths
conf=/etc/myapp/app.conf
dir=$(dirname "$conf")
cp "$conf" "$dir/app.conf.bak"Combine with realpath
abs=$(realpath -m "$1")
parent=$(dirname "$abs")Parameter expansion alternative (bash)
f=/path/to/file.txt
echo "${f%/*}" # /path/to (careful with no-slash cases)
# dirname is safer for edge cases like no slash → "."NUL-safe
find /etc -name '*.conf' -print0 |
xargs -0 -n1 dirname |
sort -uNotes / Pitfalls
dirname file(no slash) →.not empty string — important forcd.- Trailing slashes are normalized by GNU dirname.
- Don’t implement security checks with string dirname alone; canonicalize first.
- Hot loops: bash
${f%/*}is faster but handle “no slash” yourself. dirnamedoes not require the path to exist.
2026-relevant notes
- Still the readable choice in installer and devops shell scripts.
- For complex path logic, consider Python/
pathlibin larger tools. - Pair with
realpath -mwhen creating outputs under computed absolute parents.
Additional Resources
man dirname