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.

[[email protected] ~]$ basename ~/.local/bin/

As you can see, it took the full path ~/.local/bin/ and returned just the filename.

By using the -a or --multiple option, you can pass several paths, like so:

[[email protected] ~]$ basename -a ~/.local/bin/ ~/.local/bin/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.

[[email protected] ~]$ basename ~/.local/bin/ .sh

As you can see, the original filename was 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.

[[email protected] ~]$ basename -s .sh ~/.local/bin/ ~/.local/bin/ 

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?


ls -l ~/.local/bin/ | rev | cut -d'/' -f 1 | rev