[Linux] Extract Only the Filename from a Path with the basename Command

目次

Overview

The basename command extracts just the “filename” from a file path (a string including directories) by removing the directory portion.

It is primarily used in shell scripts to get filenames from log paths or to generate new filenames for backups. A key feature is that it processes the string itself regardless of whether the file actually exists on the disk.

Specifications (Arguments and Options)

Syntax

basename string [suffix]
basename [options]... string...

Main Arguments and Options

OptionDescription
-aTreats multiple arguments as file paths and displays each filename (multiple arguments).
-s <suffix>Removes the specified suffix (like an extension) from the end of the filename.
-zUses a null character (\0) as the output delimiter instead of a newline.

Basic Usage

When you provide a full path, only the filename without the directory part is output.

Command

# Extract the filename from a full path
basename /usr/local/bin/python3

Execution Result

python3

Practical Commands

Remove the Extension from a Filename

You can specify the “string to remove (extension)” as the second argument or use the -s option. This is useful when you want to handle only the filename as a variable.

# Remove .yaml from config.yaml
basename /etc/app/config.yaml .yaml

# Using the -s option (same result)
basename -s .yaml /etc/app/config.yaml

Output:

config

Extract Filenames from Multiple Paths at Once

Using the -a option, you can provide multiple paths as arguments. They are output one by one, separated by newlines.

# List only the filename parts from multiple paths
basename -a /var/log/syslog /var/log/auth.log

Output:

syslog
auth.log

Get the Filename from a Variable in a Shell Script

This is a typical pattern where you extract and use just the filename from a path variable defined in a script.

#!/bin/bash
TARGET_PATH="/var/www/html/index.php"

# Extract only the filename from the variable
FILE_NAME=$(basename "$TARGET_PATH")

echo "Target file: $FILE_NAME"

Output:

Target file: index.php

Customization Points

  • Automatic Extension Removal: Using basename $file .txt in loops helps you get the filename without the extension, which is useful for generating new names (e.g., changing .txt to .bak).
  • Contrast with dirname: While basename gets the filename, the dirname command gets the directory path. They are often used together.

Important Notes

  • String Manipulation Only: basename does not check if the specified path actually exists. It simply cuts the string after the last forward slash.
  • Handling Trailing Slashes: If a path ends with a slash (e.g., /usr/local/), the slash is ignored, and the previous element (local) is returned as the filename.
  • Missing Arguments: Running the command without any arguments will result in an error. You must provide at least one string.

Application

Backup All Files in a Directory with a Different Name

This one-liner gets the name without the extension using basename, adds a date, and copies the file.

# Rename (copy) .log files in the current directory to filename_date.bk
for file in *.log; do
  name=$(basename "$file" .log)
  cp "$file" "${name}_$(date +%Y%m%d).bk"
done

Summary

The basename command is a basic tool for path manipulation in shell scripts. It is used almost whenever you need to isolate a “pure filename” from an absolute path for processing. While you can use bash variable expansion (like ${VAR##*/}), basename is highly readable and works intuitively alongside dirname, making it a favorite for both beginners and experts. The extension removal feature is especially efficient for creating file conversion scripts.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次