Skip to content

basename Command in Linux

Summary

The basename command removes the directory and suffix from file names. It's handy for extracting the essential name component of a file path.

Introduction

The basename command in Linux is a simple yet powerful utility used to strip the directory and suffix from a filename, leaving only the base name. It's a fundamental tool for scripting and command-line operations where you need to work with just the name of a file or directory without the surrounding path or extension.

Use case and Examples

Extracting the base name from a full path

basename /path/to/my/file.txt
This command will output: file.txt. It removes the /path/to/my/ directory part, leaving only the filename.

Removing a specific suffix

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

Working with directories

basename /path/to/my/directory
This command will output: directory.

Using basename in a script

#!/bin/bash

FILE="/path/to/my/long/file_name.tar.gz"
BASE_NAME=$(basename "$FILE")
echo "The base name of the file is: $BASE_NAME"

SIMPLE_NAME=$(basename "$FILE" .tar.gz)
echo "The simplified name is: $SIMPLE_NAME"
This script demonstrates how to extract the base name and a simplified name (without the .tar.gz extension) of a file using basename and store them in variables.

Commonly used flags

Flag Description Example
-a, --multiple Support multiple arguments and treat each as a name. basename -a file1.txt file2.txt /path/to/file3.txt
-s, --suffix=SUFFIX Remove a trailing SUFFIX; implies -a. basename file.tar.gz -s .tar.gz
-z, --zero End each output line with NUL, not newline. basename -z file1.txt file2.txt (Useful for processing with xargs -0).
--help Display help information and exit. basename --help
--version Output version information and exit. basename --version


Share on Share on

Comments