dirname Command Cheat Sheet
dirname strips the last component from a file name, outputting the directory path. It is the counterpart to basename and is essential for shell scripting when handling file paths dynamically.
Synopsis
dirname [OPTION] NAME...
Basic Usage
Get Directory of a File Path
dirname /usr/bin/python3
Output:
/usr/bin
Handle Trailing Slashes
dirname ignores trailing slashes.
dirname /usr/bin/
Output:
/usr
No Slashing (Relative Path)
If the path contains no slashes, dirname outputs . (current directory).
dirname myfile.txt
Output:
.
Multiple Arguments
You can pass multiple paths at once.
dirname /home/user/docs/report.pdf /var/log/syslog
Output:
/home/user/docs
/var/log
Use in Shell Scripts
Get Script's Directory
A common pattern to ensure scripts work regardless of where they are called from.
#!/bin/bash
# Get the directory where the script is located
SCRIPT_DIR=$(dirname "$0")
# Access a config file in the same directory
source "$SCRIPT_DIR/config.conf"
echo "Running from: $SCRIPT_DIR"
Combine with readlink
If the script is a symlink, dirname alone might give the symlink's location, not the target's. Use readlink -f to resolve it first.
REAL_PATH=$(readlink -f "$0")
DIR=$(dirname "$REAL_PATH")
dirname vs basename
| Command | Input | Output |
|---|---|---|
dirname |
/home/user/file.txt |
/home/user |
basename |
/home/user/file.txt |
file.txt |
Combining Them
To get the parent directory name (e.g., just user from /home/user/file.txt):
basename $(dirname /home/user/file.txt)
# Output: user
Zero-Terminated Output (-z)
Use a NUL character instead of a newline separator. Useful for handling filenames with special characters (like newlines) when piping to xargs -0.
dirname -z /path/to/file1 /path/to/file2 | xargs -0 ...
Practical Examples
Loop Through Files and Process Parent Directory
find /var/www -name "*.conf" | while read file; do
dir=$(dirname "$file")
echo "Processing config in $dir"
# do something with $dir
done
Create Output Directory Before Copying
Ensure the destination directory exists before copying a file.
dest="/backup/2026/02/14/data.tar.gz"
mkdir -p "$(dirname "$dest")" && cp data.tar.gz "$dest"
Exit Status
| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | Error (rare, usually requires missing argument) |
Notes
dirnameis purely a string manipulator. It does not check if the directory actually exists.- It is POSIX standard, meaning it works reliably across Linux, macOS, BSD, and Unix systems.