The basename command is another gem provided by the GNU Core Utilities. It has very few options and provides a simple function, to remove the directory components from a path. It also comes in very handy for removing file extensions (SUFFIX) from a filename. In this quick tutorial, we will show you how to use the basename command and it’s options with real world examples.
Remove Path From Filename / Print Name Only
The basename command is used by simply passing it a full pathname. Without any other options or arguments, basename will take the full path and strip out the leading directory. Let’s take a look at an example.
[savona@putor ~]$ basename ~/.local/bin/mkv2mp4.sh
mkv2mp4.sh
As you can see, it took the full path ~/.local/bin/mkv2mp4.sh
and returned just the filename.
By using the -a
or --multiple
option, you can pass several paths, like so:
[savona@putor ~]$ basename -a ~/.local/bin/mkv2mp4.sh ~/.local/bin/putorius
mkv2mp4.sh
putorius
Remove File Extension (SUFFIX) From Filename
As the only Linux guy in an all Windows Shop being able to programmatically remove file extensions is a blessing. I use the basename command in a lot of my shell scripts to do just that.
To remove a file extension (SUFFIX) from a filename, simply pass the desired string as an argument after the filename. Here is an example.
[savona@putor ~]$ basename ~/.local/bin/mkv2mp4.sh .sh
mkv2mp4
As you can see, the original filename was mkv2mp4.sh
and we passed /.sh
as the suffix to be removed. The basename command returned the filename only, without the shell script extension. Don’t worry, the extension is not necessary for the script to run. No Scripts were harmed during this example.
Using the -s
or --suffix
option allows you to remove the suffix from multiple names. As the man page says, the -a
is implied. In this next example, we will remove the .sh
extension from two files.
[savona@putor ~]$ basename -s .sh ~/.local/bin/mkv2mp4.sh ~/.local/bin/set-prompt.sh
mkv2mp4
set-prompt
Here we passed the -s
option followed by the suffix we wanted to remove. Basename will process all arguments after the suffix as filenames.
Basename Command Tutorial Conclusion
Although basename doesn’t have many options, it is still a great utility. Especially if you write a lot of scripts. Sit back and ask yourself what you would be do without basename?
Hhmmm…
ls -l ~/.local/bin/mkv2mp4.sh | rev | cut -d'/' -f 1 | rev
Basename Command Resources and Links
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
1 Comment
Join Our Newsletter
Categories
- Bash Scripting (17)
- Basic Commands (51)
- Featured (7)
- Just for Fun (5)
- Linux Quick Tips (98)
- Linux Tutorials (65)
- Miscellaneous (15)
- Network Tools (6)
- Reviews (2)
- Security (32)
Very cool. I never knew about rev!