Using basename command in Linux

The basename command is useful if the full path name of a file is given but you require only the file name. It is used to strip the directory and trailing suffixes from a file name. Usually, it is used in shell scripting.

In this article, you will learn the usage of the basename command along with some examples.

The syntax of basename command in Linux

The syntax of how to use the basename command in Linux is given below.

basename NAME [SUFFIX]
basename OPTION... NAME...

You can use the following options with the basename command –

-a, --multiple – The command will support multiple arguments and treat each as a name

-s, --suffix – Removes a trailing suffix

-z, --zero – End each output line with NUL not newline

--help – Display help and exit

--version – Display the current version of the program and exit

Examples of usage of basename command in Linux

The most basic example of basename command is given below –

basename /home/lalit/names.txt

You can see the output of this command in the given image –

How to remove filename extension as well

You can use the following command if you want to remove the file name extension also.

basename -s .txt /home/lalit/names.txt

This will remove the .txt extension from names.txt.

Passing multiple inputs to basename command

You can pass multiple inputs to the basename command. The command will treat each space-separated argument as a file name. It will strip all the names and print them on the standard output.

basename /home/lalit/names.txt /home/lalit/distro.txt

If you run this you will see –

If you want to separate the output with NUL character instead of newline then you can use option -z the example of this is given below.

basename -z basename /home/lalit/names.txt /home/lalit/distro.txt

For more information about this command, you can see its man page by using –

man basename

Conclusion

This is how you can use the basename command on your system. Now if you have any query then write us in the comments below.

Leave a Comment