Bash basename Command with Examples

Written by: Linuxopsys   |   Last updated: May 5, 2023

1. Introduction

Let us imagine a situation where we have a Linux file with the absolute path. And we only need the file name. What do we do then? Definitely, we can use the available tools in Bash like sed or awk. But why go to such great lengths when we have a tailor-made tool whose sole purpose is to fetch the final component in the file path. Basename is a command-line tool for removing the directory and trailing suffix from file names. In this tutorial, we will also examine some real-world problems.

2. Syntax

The command is flexible. It enables users to provide the syntax in two different manners.

The first looks for a suffix.

basename path [suffix]

There is another syntax for basename. It can consume options. These options can be more than one.

basename option path

We are prohibited to combine the suffix with the option. 

Example:

basename /home/ubuntu/sample.txt
basename /home/ubuntu
bash basename command

Basename is a simple tool to implement. All it does is finds the last path separator (/). It displays whatever is present after that. As we can notice, the command is totally unbiased when it comes to files or directories. Its job is to simply give us the information after the final slash.

3. Arguments

The major advantage of the command is that it allows multiple inputs as arguments.

Example:

basename -a /home/ubuntu/.bashrc /etc/hosts
basename -az /home/ubuntu/.bashrc /etc/hosts
multiple inputs as arguments

To make the command interpret more than one path, we supply -a. We can also give the --multiple flag. It is used to achieve the same. Then comes a list of files, each separated by a space. In our example, we will get the name of the two files, .bashrc and hosts from their respective paths. These two file names will appear in separate lines. To separate these outputs with NULL rather than a newline we have to pass the -z flag along with it.

4. Remove trailing suffix

As we gathered, the sole role of the bash command is to give us the file name from the path. But if the file name has an extension, we get that too. We can still use the command to get rid of the extension or any suffix. This ensures we end up a clean output of just the name of the file.

Example:

basename /home/ubuntu/sample.txt .txt
basename -s .txt /home/ubuntu/sample.txt
Remove trailing suffix

We are aware the command accepts two syntaxes. They are just a different way of writing. In the first one we have to provide the path and the extension we want to be trimmed from the final output. In the latter case, we have the -s option which accepts the extension we want to remove. In both cases, the basename should produce the result "sample.txt". As we have provided the suffix, the output will be trimmed further by removing the .txt from the result. We will get the final output "sample". If we provide an imaginary suffix or one that is not at the end, the outcome remains the same. It will assume there was no suffix.

We can, with certain limitations, combine -s and -a flag to trim extensions from multiple inputs.

Example:

basename -as .txt /home/ubuntu/readmecopy.txt /home/ubuntu/readme.txt
basename -as .txt /home/ubuntu/readmecopy.txt /home/ubuntu/config.cfg

In the first case, we have asked the command to remove the .txt extension from multiple inputs. But there is a loophole. We cannot assign individual suffices. That won’t work. Our hand is forced as we can only provide one suffix to all the file paths. If multiple files with different extensions exist, then it will trim the ones whose extensions match with the supplied. In our case, we get "sample" and "sample.cfg" as the eventual output. They will be separated by a line break.

5. Basename Real-time Applications

We have understood that the command is simple enough to try out. Furthermore, it doesn’t have too many options making it relatively easy for challenging problems. We will look at a couple of examples where we will require the use of this command

5.1. Renaming files with extensions

Very often we will have text files with the extension .txt. Say we want to rename those files with the same name but with a different extension. This is where we have the basename utility at our disposal.

Example:

#!/bin/bash
for file in *txt; do
if [ -f $file ]; then
 mv $file `basename $file .txt`.cfg
fi
done
Renaming files with extensions

We are looking for txt files in this example. We have a for loop to operate over each file. We first check if the file exists. If only it exists, we calculate the basename. This is after trimming the original extension. We then move the txt file to the same file name with a .cfg extension. 

5.2. Working with URLs

There is a lot of similarity between URLs and Linux file paths in terms of the nomenclature and the path separators. Both use the slash (\). Basename command also acts on this slash. At times we have a list of URLs and we want to extract the final name and save the results to a file or build a new url with these file names.

Example:

#!/bin/bash
url1="https://www.rediff.com/cricket/report/20230504.htm"                     
url2="https://www.rediff.com/cricket/report/20230503.htm"
url3="https://www.rediff.com/cricket/report/20230502.htm"
basename -a $url1 $url2 $url3 | tee output.txt
while read line
do
    echo https://www.mywebsite.com/myarticles/$line
done < output.txt
from URLs extract the final name

We have a bunch of URLs, from which we are extracting the basename with the extension. We have used the -a flag to have multiple inputs separated by a space. In our case, the inputs are stored in variables. The result of the basename command is stored in output.txt. Now we iterate over the file line by line and display a new set of URLs with the same basename.

Basename command Options

We have tabulated the options available with the command.

OptionsDescription
-a or
--multiple
This option supports multiple arguments. We can still provide a single input with the -a or --multiple flag.
-sor--suffixThis option removes a trailing suffix. A popular example is file extension
-zThis option separates the output with NULL instead of a newline. 
-versionThis displays the version number of the command and exits.
-helpThis option is used to show us the information needed if we are stuck somewhere. It is similar to a readme document. It displays the help content and exits.

Conclusion

  • Basename is a simple enough command with a fixed number of options.
  • These options can be used with certain limitations.
  • We usually use it to display the filename with or without the extension.
  • We have the option to trim the extension from the file name too.
SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment