basename Command
The basename command is used to extract the filename or the last component of a pathname. It can also remove a specified suffix from the filename.
Syntax
basename NAME [SUFFIX]
basename OPTION... NAME...
basename OPTION... NAME...
Description
basename prints the name of the file or directory without its leading directory components. If a suffix is provided, it will be removed from the name. This command is often used in shell scripts to manipulate file paths.
Common uses include:
- Extracting just the filename from a full path
- Removing file extensions
- Processing multiple pathnames
Common Options
| Option | Description |
|---|---|
-a, --multiple |
Support multiple arguments and treat each as a NAME |
-s, --suffix=SUFFIX |
Remove a trailing SUFFIX from NAME |
--zero |
End each output line with NUL, not newline |
Examples
Extract filename from a path
basename /home/user/documents/report.txt
# Output: report.txt
# Output: report.txt
This example extracts just the filename from the given absolute path.
Extract filename and remove suffix
basename /home/user/documents/report.txt .txt
# Output: report
# Output: report
This example removes the .txt extension from the filename.
Process multiple files
basename -a /dir1/file1.log /dir2/file2.tar.gz
# Output: # file1.log # file2.tar.gz
# Output: # file1.log # file2.tar.gz
Using the -a option to process multiple pathnames.
Remove suffix from multiple files
basename -a -s .log /var/log/syslog.log /var/log/auth.log
# Output: # syslog # auth
# Output: # syslog # auth
Removes the .log suffix from multiple log files.