basename – strip directory from filename

basename strips the directory path from a filename, optionally removing a suffix.
Synopsis
basename PATH [SUFFIX]
basename -s SUFFIX PATH...
Examples
Strip directory
$ basename /var/log/syslog
syslog
$ basename /home/greys/documents/report.pdf
report.pdf
Strip suffix too
$ basename /home/greys/script.sh .sh
script
$ basename report.pdf .pdf
report
Multiple files
$ basename -a /path/file1.txt /path/file2.txt
file1.txt
file2.txt
$ basename -s .txt /path/file1.txt /path/file2.txt
file1
file2
In Scripts
Get script name
#!/bin/bash
SCRIPT_NAME=$(basename "$0")
echo "Running: $SCRIPT_NAME"
Process files
for file in /data/*.csv; do
name=$(basename "$file" .csv)
echo "Processing: $name"
done
Rename files
for file in *.JPEG; do
base=$(basename "$file" .JPEG)
mv "$file" "${base}.jpg"
done
Shell Alternative
Using parameter expansion (faster, no subprocess):
path="/var/log/syslog"
# Remove directory
${path##*/} # Result: syslog
# Remove extension
filename="report.pdf"
${filename%.*} # Result: report
Tips
- Use in loops: Essential for batch file processing
- Parameter expansion: Faster than basename for simple cases
- Works with any path: Doesn’t check if file exists
- Pair with dirname: Together they split paths completely
See Also
Related Commands
- dirname — Strip filename, keep directory
- realpath — Resolve to absolute path
- readlink — Print symlink target






