Bash basename: A Beginner’s Guide

bash basename

In Bash scripting, the basename command is used to extract the filename or directory name from a given path. It is a simple yet powerful command that can be used to manipulate file paths and names.

Syntax

The syntax for the basename command is as follows:

basename [options] filename

Here, filename is the path of the file or directory whose name you want to extract. The options are optional and can be used to modify the behavior of the basename command.

Examples

Let’s take a look at some examples to understand how the basename command works:

Example 1: Extracting Filename

Suppose you have a file named example.txt in your current directory, and you want to extract its filename. You can use the basename command as follows:

$ basename example.txt

This will output:

example.txt

Example 2: Extracting Directory Name

Suppose you have a file named example.txt in the directory /home/user/documents/, and you want to extract the name of its parent directory. You can use the basename command as follows:

$ basename /home/user/documents/example.txt

This will output:

documents

Example 3: Removing File Extension

Suppose you have a file named example.txt in your current directory, and you want to remove its file extension. You can use the basename command in combination with the cut command as follows:

$ basename example.txt | cut -d. -f1

This will output:

example

Here, the cut command is used to remove the file extension from the output of the basename command.

Options

The basename command comes with a few options that can be used to modify its behavior. Let’s take a look at some of the most commonly used options:

-a or –multiple

This option is used to extract the basename of multiple files at once. For example:

$ basename -a /home/user/documents/*

This will output the basename of all files in the /home/user/documents/ directory.

-s or –suffix

This option is used to remove a given suffix from the basename. For example:

$ basename -s .txt example.txt

This will output:

example

Here, the .txt suffix is removed from the basename.

-z or –zero

This option is used to separate the basenames of multiple files with a null character instead of a newline character. For example:

$ basename -z /home/user/documents/*

This will output the basename of all files in the /home/user/documents/ directory, separated by a null character.

Conclusion

In this article, we covered the basename command in Bash scripting. We discussed its syntax, provided examples, and explained some of the most commonly used options. The basename command is a powerful tool that can be used to manipulate file paths and names in a variety of ways.