what is basename command

What is Basename Command in Shell Script

Sometimes you may need to extract the file name from a given path. For such use cases, Linux shells provide basename function, which strips directory and trailing suffix from given path values. In this article, we will learn how to use basename command in shell script.

What is Basename Command in Shell Script

There are couple of ways to use basename command in shell script.

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

Basename command takes a path and prints the last part of it. It will also remove any trailing slashes. But it will retain file extensions. Here are some examples.

$ basename /home/data.txt
$ basename /home/data/
$ basename /home/data

Using Multiple Inputs

If you want to get basename of multiple paths then you need to use -a or –multiple option followed by each path in a space-separated manner. Here is an example to get basename of /home/projects and /home/ubuntu/.

$ basename -a /home/ubuntu/ /home/projects

Remove Trailing Suffix

You can also use basename command to remove trailing suffix from file path by mentioning it as second argument.

$ basename /home/data.txt .txt

You may also use -s option and specify suffix before mentioning the file path.

$ basename -s .txt /home/data.txt

You can also use it in combination with -a option described above, to remove suffixes of multiple files.

$ basename -a -s .txt /home/data.txt /home/projects/data1.txt

This technique is used to remove extensions from file names.

That’s it. In this short article, we have learnt what is basename and how to use it.

Also read:

How to Compare Strings in Python
How to Copy List in Python
How to Copy Files in Python
How to Comment in Python
Git Rename Local & Remote Branch

Leave a Reply

Your email address will not be published. Required fields are marked *