How to Extract Filenames Using the basename Command in Linux

When you are writing a bash script to process hundreds of files in a directory, your script will often read the absolute path of a file (e.g., /var/log/apache2/access_log_january.txt). If your script needs to create a new backup file based on that name, you do not want to accidentally name the backup /var/log/apache2/access_log_january.txt_backup.zip because you failed to strip away the directory path and the file extension. To safely and easily extract just the core name of a file, Linux provides the basename command.

How to Strip the Directory Path

The primary function of the basename utility is to delete everything in a file path up to and including the final forward slash (/), leaving you with only the name of the file itself.

You use it by passing the full path as an argument:

basename /usr/local/bin/python3

The terminal will instantly output:

python3

This is incredibly useful inside a bash script when combined with command substitution. For example, you can store the clean name in a variable:

CLEAN_NAME=$(basename /home/user/documents/report.pdf)
echo "The file is named $CLEAN_NAME"

This script will output: The file is named report.pdf.

How to Strip the File Suffix (Extension)

While stripping the directory path is helpful, you are still left with the .pdf file extension. If you are writing a script to convert that PDF into a JPEG, you need to extract just the word “report” so you can append the new .jpg extension to it.

The basename command can strip both the directory path and the file suffix simultaneously. You simply provide the suffix you want to delete as a second argument.

basename /home/user/documents/report.pdf .pdf

The terminal will process the path, strip everything up to the final slash, then look at the end of the string, find the .pdf suffix you specified, and delete that too. The output will be perfectly clean:

report

The Alternative: The dirname Command

It is worth noting that basename has an exact opposite counterpart called dirname. While basename extracts the file and deletes the path, dirname extracts the path and deletes the file.

dirname /home/user/documents/report.pdf

This command will output: /home/user/documents. By using basename and dirname together in your bash scripts, you can safely parse, deconstruct, and rebuild file paths dynamically without relying on complex and error-prone regular expressions.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.