Home > File & Directory Management > basename

basename: Extract Filename from Path

The basename command removes directory components from a given file path, extracting the pure filename or directory name. It is commonly used in shell scripts when only the filename is needed, returning the last component of the path.

Overview

basename extracts the string after the last slash (/) in a file path string and returns the filename or directory name. It can also optionally remove a suffix.

Key Features

  • Extracts filename from file path
  • Optionally removes suffix
  • Can process multiple paths at once

Key Options

Behavior Control

Generated command:

Try combining the commands.

Description:

`basename` Executes the command.

Combine the above options to virtually execute commands with AI.

Usage Examples

Basic Usage

basename /home/user/documents/report.txt

Extracts the filename from a given path.

Removing Suffix

basename /home/user/documents/report.txt .txt

Removes a specific suffix from the extracted filename.

Processing Directory Path

basename /home/user/documents/

Returns the directory name if the last component of the path is a directory. Trailing slashes are ignored.

Processing Multiple Paths

basename -a /path/to/file1.txt /path/to/file2.log

Extracts filenames from multiple paths at once using the -a option.

Extracting Current Directory Name

basename $(pwd)

Extracts the name of the current working directory.

Tips & Notes

The basename command is very useful for handling file paths in shell scripts.

Usage Tips

  • Can be used with `dirname` to separate path and filename.
  • Useful for extracting only the filename from a path stored in a variable in shell scripts.
  • When removing a suffix, the suffix must exactly match the end of the filename. Partial matches are not applied.

Related commands

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


Same category commands