dirname
Overview
The dirname command strips the last component from file names, returning the directory path portion. It’s the complement to basename for path manipulation.
Syntax
dirname name...Common Options
| Option | Description |
|---|---|
-z |
End output with NUL character |
Key Use Cases
- Extract directory path
- Script directory detection
- Relative path calculation
- File organization
- Path validation
Examples with Explanations
Example 1: Basic Usage
dirname /path/to/file.txtReturns: /path/to
Example 2: Current Directory
dirname file.txtReturns: .
Example 3: Script Directory
SCRIPT_DIR=$(dirname "$0")Gets the directory containing the script
Common Usage Patterns
Change to script directory:
cd "$(dirname "$0")"Create parent directories:
mkdir -p "$(dirname "$target_file")"Relative path operations:
parent_dir=$(dirname "$PWD")
Best Practices
- Quote paths to handle spaces
- Use with basename for complete path parsing
- Consider absolute vs relative paths
- Handle edge cases (root directory, current directory)
Integration Examples
Backup to parent directory:
backup_dir="$(dirname "$PWD")/backups"Config file location:
config_dir="$(dirname "$0")/config"