Skip to content

basename Command in Linux

Summary

The basename command extracts the filename from a given path, removing any directory components. It's useful for scripts and commands where you need just the filename without its location.

Introduction

The basename command is a utility in Linux (and other Unix-like systems) that strips the directory and suffix from a filename. Essentially, it extracts the last component of a pathname. This can be extremely useful in shell scripts when you need to isolate the filename from its full path.

Use case and Examples

Basic Usage

basename /path/to/my/file.txt
This will output: file.txt. It removes the directory part (/path/to/my/) from the input.

Removing a Specific Suffix

basename /path/to/my/file.txt .txt
This will output: file. It removes both the directory part and the specified suffix (.txt).

Using with Variables

FILE_PATH="/home/user/documents/report.pdf"
FILENAME=$(basename "$FILE_PATH")
echo "Filename: $FILENAME"
This will output: Filename: report.pdf. This demonstrates using basename to extract the filename from a variable.

Handling Directory Names

basename /path/to/a/directory
This will output: directory. It works on both files and directories.

Multiple arguments

basename /path/to/file1.txt /path/to/file2.txt
This will output:
file1.txt
file2.txt
You can pass multiple path arguments to the basename command, with each filename printed on a new line.

Commonly used flags

Flag Description Example
--help Displays help information. basename --help
--version Displays version information. basename --version
-a or --multiple Supports multiple arguments. basename -a /path/to/file1.txt /path/to/file2.txt
-s or --suffix=SUFFIX Remove a trailing SUFFIX; implies -a. basename -s .txt /path/to/file.txt
-z or --zero End each output line with NUL, not newline basename -z /path/to/file.txt


Share on Share on

Comments