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.
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.
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
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
It will give us the following output on the screen:
We can also apply it to files:
Also, we can define a suffix with the
-s option that will be omitted in the screen output:
basename -s .conf /etc/nsswitch.conf
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
Or visit the section dedicated to
basename from the GNU Core Utils website.
The basename command is quite simple but can be very useful in configuration scripts or file management via terminal.