The basename
command in Linux is used to extract the last element of a file path. This is particularly helpful in bash scripts where you only need the file name from a complete file path. Additionally, it allows you to remove file extensions or suffixes.
In this guide, we’ll explore how to use the basename
command with examples, showcasing its options and capabilities.
Basic Syntax of basename
The basename
command supports the following syntax:
$ basename NAME [SUFFIX]
$ basename OPTION... NAME...
NAME: The full file path or string to extract the base name from.
SUFFIX: An optional string that will be removed from the output.
The command prints the last component of the file path, and if needed, removes the specified suffix.
Extracting the File Name
To get the last part of a file path, simply pass the file path to basename
:
$ basename /usr/bin/ls
# output
ls
Here, basename
strips the leading directories, leaving only the file name.
Handling Trailing Slashes
The basename
command will ignore any trailing slashes. For example:
$ basename /usr/share/apps/
# output
apps
Without the trailing slash:
$ basename /usr/share/apps
# output
apps
In both cases, basename
returns the last directory in the path.
Using basename
with Multiple Inputs
The -a
or --multiple
option allows you to process multiple file paths in one go:
$ basename -a /bin/ls /bin/lsd
# output
ls
lsd
This command prints the base name of each file path provided.
Removing a Trailing Suffix
If you want to remove a specific suffix from the file name, you can provide it as a second argument:
$ basename /bin/systemctl ctl
# output
system
Here, basename
strips the trailing ctl
from the file name.
Removing File Extensions
You can also use this feature to strip common file extensions like .conf
:
$ basename /etc/resolv.conf .conf
# output
resolv
Alternatively, you can use the -s
or --suffix
option to achieve the same result:
$ basename -s .conf /etc/resolv.conf
# output
resolv
Stripping Suffixes from Multiple Files
The -s
option can be used with multiple files to remove the same suffix:
$ basename -s .conf /etc/resolv.conf /etc/db.conf
# output
resolv
db
Conclusion
The basename
command is a simple yet powerful tool for handling file paths in Linux. It’s especially useful in bash scripting for extracting file names and removing extensions. With the options to process multiple files and strip suffixes, it's a handy command to have in your toolbox.
That’s all for this guide! If you found it useful, make sure to share it with others and subscribe for more Linux, sysadmin, and DevOps content.