Linux basename dirname Guide - ryzendew/Linux-Tips-and-Tricks GitHub Wiki
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
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
- readlink Guide - Symbolic link resolution
- realpath Guide - Absolute path resolution
- Bash Scripting Guide - Scripting basics
- basename Documentation:
man basename - dirname Documentation:
man dirname
This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.