Linux Command: basename
Strip directory and suffix from filenames
basename strips directory paths and optionally file extensions from filenames. It extracts just the filename component from a full path, making it essential for file processing scripts. basename takes a path and returns only the final component. With a second argument, it also removes a specified suffix (typically the file extension). basename is commonly used in scripts to get filenames from full paths, generate output filenames based on input filenames, and strip extensions for format conversion scripts.
Syntax
basename NAME [SUFFIX]Key Options
PATHโ Strip directory from pathPATH SUFFIXโ Strip directory and suffix-sโ Remove suffix (alternative syntax)-aโ Process multiple arguments
Examples
Get filename from path
basename /var/log/nginx/access.logOutput: access.log
Remove extension
basename report.pdf .pdfOutput: report
In a script
for f in /data/*.csv; do echo "Processing $(basename "$f" .csv)"; doneOutput: Processing users\nProcessing orders
Pro Tips
- base=$(basename "$file" .jpg); convert "$file" "${base}.png" โ converts image format using the original base name.
- basename gets the filename; dirname gets the directory. Together they split a path: dirname /a/b/c โ /a/b, basename /a/b/c โ c.
- Always quote: basename "$filepath". Filenames with spaces will break without quotes.
Learn more: Full basename reference โ
Related Resources