Skip to content

Linux basename dirname Guide

Mattscreative edited this page Dec 5, 2025 · 2 revisions

Linux basename and dirname Guide

Complete beginner-friendly guide to basename and dirname on Linux, covering Arch Linux, CachyOS, and other distributions including path manipulation, filename extraction, and directory path extraction.


Table of Contents

  1. basename Basics
  2. dirname Basics
  3. Path Manipulation
  4. Script Usage
  5. Troubleshooting

basename Basics

Extract Filename

Basic usage:

# Extract filename
basename /path/to/file.txt

# Output: file.txt

Remove Suffix

Remove extension:

# Remove suffix
basename /path/to/file.txt .txt

# Output: file

dirname Basics

Extract Directory

Basic usage:

# Extract directory
dirname /path/to/file.txt

# Output: /path/to

Parent Directory

Get parent:

# Parent directory
dirname /path/to/dir/

# Output: /path/to

Path Manipulation

Combined Usage

Both commands:

# Get directory and filename
FILE="/path/to/file.txt"
DIR=$(dirname "$FILE")
NAME=$(basename "$FILE")

echo "Directory: $DIR"
echo "Filename: $NAME"

Remove Extension

Strip extension:

# Remove extension
basename file.txt .txt

# Output: file

Script Usage

Path Processing

In scripts:

#!/bin/bash
FILE="/path/to/file.txt"

# Get components
DIR=$(dirname "$FILE")
NAME=$(basename "$FILE")
BASE=$(basename "$FILE" .txt)

echo "Full path: $FILE"
echo "Directory: $DIR"
echo "Filename: $NAME"
echo "Base name: $BASE"

Troubleshooting

Commands Not Found

Check installation:

# basename and dirname are part of coreutils
# Usually pre-installed

# Check commands
which basename
which dirname

Summary

This guide covered basename and dirname usage, path manipulation, and filename extraction for Arch Linux, CachyOS, and other distributions.


Next Steps


This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.

Clone this wiki locally