basename
Overview
The basename
command strips directory and suffix from filenames, returning just the filename portion of a path. It’s essential for path manipulation in scripts.
Syntax
basename name [suffix]
basename option... name...
Common Options
Option | Description |
---|---|
-a |
Support multiple arguments |
-s suffix |
Remove trailing suffix |
-z |
End output with NUL character |
Key Use Cases
- Extract filename from path
- Remove file extensions
- Script path manipulation
- Batch file processing
- Log file naming
Examples with Explanations
Example 1: Basic Usage
basename /path/to/file.txt
Returns: file.txt
Example 2: Remove Extension
basename /path/to/file.txt .txt
Returns: file
Example 3: Multiple Files
basename -a /path/file1.txt /other/file2.log
Returns: file1.txt
and file2.log
Common Usage Patterns
Script naming:
SCRIPT_NAME=$(basename "$0")
Remove extensions:
basename "$file" .conf
Process multiple files:
for file in *.txt; do name=$(basename "$file" .txt) echo "Processing: $name" done
Best Practices
- Quote variables to handle spaces
- Use with dirname for complete path manipulation
- Consider using parameter expansion as alternative
- Test with edge cases (empty paths, root directory)
Integration Examples
Backup script:
backup_name="backup-$(basename "$PWD")-$(date +%Y%m%d)"
Log rotation:
logname=$(basename "$logfile" .log) mv "$logfile" "${logname}-$(date +%Y%m%d).log"