How to use the basename command?

Scripting in Linux requires a solid knowledge of the commands provided by the shell. Some of them are quite useful and somewhat complex to use like the rm command and others are simpler like the basename command. The latter, although with a somewhat limited utility, is essential in many scripts.

The basename command

In the documentation of the command, we have the following definition

Print NAME with any leading directory components removed. If specified, also remove a trailing SUFFIX.

In addition to this definition, it must be said that the basename command belongs to the GNU Core Utils suite that is present in all Linux distributions. So unlike the nmap command, we do not have to install anything and when we open the terminal we can use it.

This command may not seem very useful for a regular user, but it is widely used in configuration scripts where it is required.

Using the basename command

The basename command is quite simple to use and has a common syntax like the rest of the Unix family of commands.

The basic syntax of the command is as follows

basename NAME [SUFFIX]

or if you will use some of its options:

basename OPTION... NAME...

Some of the options provided by the basename command are the following:

-a, --multiple       support multiple arguments and treat each as a NAME
-s, --suffix=SUFFIX: This option removes a trailing SUFFIX; implies -a
-z, --zero:  end each output line with NUL, not newline

Using the basename command

As we have noticed, the basename command extracts the name of the file or folder that we assign as a parameter, so its use is as follows

basename /etc/

It will give us the following output on the screen:

etc

We can also apply it to files:

basename /etc/nsswitch.conf

Output:

nsswitch.conf

Also, we can define a suffix with the -s option that will be omitted in the screen output:

basename -s .conf /etc/nsswitch.conf

Output:

nsswitch

In this way, you can set what you want to display when executing the command.

If you want to know more about the operation of the command, you can consult the help from the main menu

basename --help

Or visit the section dedicated to basename from the GNU Core Utils website.

Conclusion

The basename command is quite simple but can be very useful in configuration scripts or file management via terminal.

Scroll to Top