Home > File & Directory Management > basename

basename Command Guide

`basename` command is used to extract only the pure filename (or directory name) from a file path, excluding the directory part. It is very useful when you need to handle file names cleanly in shell scripts.

basename Overview

`basename` returns the string after the last slash (/) in a given path string. In other words, it is a command that retrieves only the name part from the full path of a file or directory.

Role of basename

The `basename` command is primarily used in the following situations:

Key Application Areas

  • Shell Scripts: When extracting only filenames to perform specific operations in file processing loops.
  • Log Analysis: When filtering only filenames from logs that include paths to create statistical data.
  • Automation: When generating or processing other filenames based on a file name.

Main basename Command Options

The `basename` command is simple, but it can perform additional functions, such as removing specific extensions, through useful options.

1. Basic Usage

2. Extension Removal Option

Generated command:

Try combining the commands.

Description:

`basename` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Practice filename extraction and processing through practical examples of the `basename` command.

Extract filename from file path

basename /home/user/documents/report.pdf

Extracts the pure filename `report.pdf` from the path `/home/user/documents/report.pdf`.

Extract last directory name from directory path

basename /var/log/apache2/

Extracts the last directory name `apache2` from the path `/var/log/apache2/`.

Remove file extension

basename image.png .png

Removes the `.png` extension from the filename `image.png`, leaving only `image`.

Remove complex extension

basename archive.tar.gz .tar.gz

Removes the `.tar.gz` extension from `archive.tar.gz`, leaving only `archive`.

Example of basename usage in a script

for file in *.log; do
  base_name=$(basename "$file" .log)
  echo "Processing: $base_name"
done

An example shell script that uses a for loop to print only the base names of files with the `.log` extension.


Related commands

These are commands that are functionally similar or are commonly used together.


Same category commands