Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the last dirname/filename in a file path argument in Bash?
Working with file paths is a common task in Bash scripting, and extracting the last component (filename) or parent directory name from a path is frequently needed. Bash provides several utilities to manipulate file paths effectively, with basename and dirname being the most commonly used commands.
Getting the Last Filename with basename
The basename command extracts the final component from a file path, removing all preceding directory components. This is useful when you need just the filename from a complete path.
Basic Usage
basename /path/to/file.txt
file.txt
Working with Environment Variables
You can use basename with environment variables like $PATH. Since $PATH contains multiple directories separated by colons, basename will return the last directory name.
echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Library/Apple/usr/bin:/Users/immukul/.cargo/bin
basename $PATH
bin
Getting Parent Directory Names with dirname
The dirname command returns the directory path by removing the last component. When combined with basename, you can extract directory names at different levels.
Getting the Second-to-Last Component
echo $(basename $(dirname $PATH))
.cargo
Getting the Third-to-Last Component
echo $(basename $(dirname $(dirname $PATH)))
immukul
Alternative Methods
Bash also provides parameter expansion methods for path manipulation without external commands:
# Get basename using parameter expansion
path="/home/user/documents/file.txt"
echo ${path##*/}
# Get dirname using parameter expansion
echo ${path%/*}
file.txt /home/user/documents
Common Use Cases
| Task | Command | Example Result |
|---|---|---|
| Extract filename | basename /path/to/file.txt | file.txt |
| Extract directory | dirname /path/to/file.txt | /path/to |
| Remove file extension | basename /path/file.txt .txt | file |
| Get parent directory name | basename $(dirname /path/to/file) | to |
Conclusion
The basename and dirname commands are essential tools for path manipulation in Bash. basename extracts the final component from a path, while dirname returns the parent directory. Combining these commands allows you to navigate and extract components at any level of a file path hierarchy.
