basename — Extract the file name from a path
Linux / File and disk management / basename.html
Keeps only the last component of a path and optionally strips a suffix.
Basic Information
| Command Name | basename |
|---|---|
| One-line Introduction | Keeps only the last component of a path and optionally strips a suffix. |
| Provided by | GNU coreutils (installed by default on all Linux distributions) |
| Official Documentation | https://man7.org/linux/man-pages/man1/basename.1.html |
| Supported Operating Systems | Linux, macOS, BSD, WSL |
| Installation Status | Installed by default (no separate installation needed) |
| Category | Linux file and disk management (tags: path, filename, script) |
What is this command?
basename extracts just the file name from a path. A second argument removes that suffix as well.
It is useful for swapping extensions or embedding a file name in log messages.
What problems does it solve?
- You only need the name from a path
- You are converting a file to another extension
- You want the file name in a message
- A loop needs the target name
Key features
Get the file name
Prints only the last component.
- When to use: You need just the name
- What you get: The file name including extension
- Limitations: A directory path yields the directory name.
Strip a suffix
The second argument removes a suffix.
- When to use: You build a sibling file name
- What you get: The name without the suffix
- Limitations: Only an exact suffix match is removed.
Handle multiple arguments
-a handles several paths.
- When to use: In batch conversion scripts
- What you get: A name per path
- Limitations: -a is a GNU extension and may be missing elsewhere.
Installation and usage
Check whether it is installed
basename --version
sudo apt install coreutils # Debian/Ubuntu sudo dnf install coreutils # Fedora
Real-world examples
Get the name
Get only the file name.
basename /var/log/nginx/access.log
Swap the extension
Keep the name and add a new extension.
name=$(basename report.csv .csv)
echo "$name.md"
Several paths
Print names for two paths.
basename -a /etc/hosts /etc/fstab