How to Use the basename Command in Linux Bash

Yahya Irmak Feb 02, 2024
  1. Use the basename Command to Strip Directory From Filename in Linux Bash
  2. Use the basename Command to Remove Suffix From Filename in Linux Bash
How to Use the basename Command in Linux Bash

Sometimes, in Bash scripting, you may want to get the filename, not the entire path, and even get rid of the extension at the end of a file.

This article will explain using the basename command to strip the directory and suffix from a filename in Linux Bash.

Use the basename Command to Strip Directory From Filename in Linux Bash

The basename command strips the directory from the filenames. It prints filename with any leading directory components removed.

After the basename command name, type the filename.

basename /usr/bin/uname

In the example above, the basename command deletes the /usr/bin directory and prints uname to the screen.

strip directory from filename

You can also give multiple filenames with the -a or --multiple parameters. The command performs the same operation for each argument and prints each on a new line with these parameters.

All output is written the same line (not the newline) using the -z or --zero parameter.

basename -a folder1/file1 folder2/file2
basename -az folder1/file1 folder2/file2

We will first remove the directory from both filenames and print both on a new line in this example. Then, we will print both on the same line with the -z parameter.

strip directory from multiple filenames

Use the basename Command to Remove Suffix From Filename in Linux Bash

The basename command also deletes the file suffix and the directory if specified. To remove the file’s suffix, type the suffix you want to delete at the end of the command.

You can also use the -s or --suffix parameter to delete the suffix.

The example below will delete both the directory and the .py extension.

basename tools/example.py .py
basename -s .py tools/example.py

remove suffix from filename

Get Suffix From Filename in Linux Bash

We can use the following code to get the suffix of a file. First, we strip the directory using the basename command and store it in the filename variable.

Then, using the double hash with the expression suffix=${filename##*.}, we get the suffix.

filename=$(basename "$1" )
suffix=${filename##*.}
echo $suffix

We get all the extensions after the first dot, not just the last suffix, using a single hash for files with multiple extensions like .en.md.

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Bash Command