Basename Command in Linux

16

In Linux, the basename command prints the last element of a file path. This is especially useful in bash scripts where the file name needs to be extracted from a long file line.

The “basename” takes a filename and prints the filename’s last portion. It can also delete any following suffix if needed.

Let’s use different examples to understand the basename command in Linux.

Syntax:

It supports two syntaxes:

  • basename Path Suffix
  • basename option pathname

In the first syntax, add a suffix at the end of path/filename, and in the second, we can add an option. We cannot add an option with a suffix.

Using basename command with filename:

Create the file by using the touch command:

In this example, the file is named bash.txt:

Now, let’s use the file with the basename command:

Basename Command in Linux 1617239669 804 Basename Command in Linux

Basename Command in Linux 1617239669 977 Basename Command in Linux

It will print the filename only.

Removing any / trailing character:

Use the following command to remove any trailing/character from the path:

Basename Command in Linux 1617239669 54 Basename Command in Linux

Remove trailing suffix:

Transfer the suffix as a second argument to delete any trailing suffix from the file name:

$ basename file_pathsuufix  suffix

Basename Command in Linux 1617239670 905 Basename Command in Linux

Basename Command in Linux 1617239670 820 Basename Command in Linux

Normally, this command is used to remove file extension:

Basename Command in Linux 1617239671 573 Basename Command in Linux

Another way is to remove the trailing suffix from the file:

$ basename –s suffix filepathsuffix

Basename Command in Linux 1617239671 600 Basename Command in Linux

Print or remove multiple files:

We can print or remove multiple file suffixes from files by using the -a flag. To print multiple filenames, use the following command:

$ basename –a filepath1 filepath2

Basename Command in Linux 1617239672 901 Basename Command in Linux

We can also remove trailing suffixes from multiple files by using the below command:

$ basename –a –s suffix Filepath1_suffix  filepath2_suffix

Basename Command in Linux 1617239672 431 Basename Command in Linux

Conclusion:

A basename is a command-line tool that removes the directory and suffix from assigned file names. The basename command print the last portion of the file name on the terminal. This post describes the basename command in detail.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More