Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • 1. Introduction
  • 2. Syntax
  • 3. Arguments
  • 4. Remove trailing suffix
  • 5. Basename Real-time Applications
  • Basename command Options
  • Conclusion

Bash basename Command with Examples

PreviousHow to Use While Loop in Bash for Efficient ScriptingNextHow to Create Multiline Strings in Bash

Last updated 1 year ago

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

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

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

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/bashfor file in *txt; doif [ -f $file ]; then mv $file `basename $file .txt`.cfgfidone

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/bashurl1="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.txtwhile read linedo echo https://www.mywebsite.com/myarticles/$linedone < output.txt

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.

Options
Description

-a or --multiple

This option supports multiple arguments. We can still provide a single input with the -a or --multiple flag.

-sor--suffix

This option removes a trailing suffix. A popular example is file extension

-z

This option separates the output with NULL instead of a newline.

-version

This displays the version number of the command and exits.

-help

This 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.

multiple inputs as arguments
bash basename command
Remove trailing suffix
from URLs extract the final name
Renaming files with extensions