basename: strip directory and file extension or suffix from path
displays the main part of a directory or file name, stripping directories and file name suffix
Typical usage: automation tasks, shell scriptingIntroduction into basename
The basename tool is a helper tool for use in shell scripts to easily strip parts of a path, so that only the file name is returned. This simplifies automation tasks where you might need the core part of the file name and add a new extension to it, like when processing files and converting them.
Installation
When basename is not installed by default, it can be added to the system using the relevant software package.
Package information for basename
Operating system | Package name | Installation |
---|---|---|
AlmaLinux | coreutils |
|
Arch Linux | coreutils |
|
Debian | coreutils |
|
Fedora | coreutils |
|
Red Hat Enterprise Linux | coreutils |
|
Rocky Linux | coreutils |
|
openSUSE | coreutils |
|
Ubuntu | coreutils |
|
Your Linux distribution using a different package? Share your feedback.
Usage
Available options
Long option | Short option | Description |
---|---|---|
--multiple | -a | Strip multiple paths |
--suffix=SUFFIX | -s | Provide the file extension or suffix to strip |
--zero | -z | Terminate output lines with NUL (\0), not a newline (\n) |
Missing an option in this overview? Share your feedback.
Examples using basename
Return the last part of a directory name
basename /usr/share/doc
Output: doc
Only return the file name (passwd) from the full path
basename /etc/passwd
Output: passwd
Strip the .yaml extension from the file name
basename -s .yaml slab.yaml
Output: slab
Provide multiple paths and return each stripped version of them
basename -a /etc/passwd /etc/shadow
Output: passwd shadow (both are displayed each on one line, can be directly used in a for loop)
Frequently Asked Questions
What is the basename command and its purpose?
The basename command is a command-line tool to strip the directories above the path and an optional file name suffix
Which package provides the basename command?
The command basename is provided by the coreutils package.
Related and similar commands
Linux has a lot of tools and commands available and sometimes you just need that little other tool. Here is a list of commands that are similar or related to basename:
Command | Category | Summary |
---|---|---|
fuser | files and sockets | Show processes using a file or socket |
lsfd | files | Shows open file descriptors for processes |
nice | processes | Runs commands with specified priority |
rev | data | Shows text in reverse order |
watch | processes | Monitors changes in output of specified command |