- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the last dirname/filename in a file path argument in Bash?
We make use of the bash files to store different variables that we normally refer to as the environment variables. We can later access these variables easily by just printing them with the help of the echo utility command tha linux provides us with.
Example
Print the $PATH environment variable.
Command
echo $PATH
Output
immukul@192 src % echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Library/Apple/usr/bin:/Us ers/immukul/.cargo/bin
Now as we can see that the PATH environment variable is made of different directories, and suppose we want the last file name from the path variable.
In that case, we would make use of the base name command utility that Linux provides us with.
The base name command is used to remove the directory path and return the last filename present in the variable.
Command
basename $PATH
Output
bin
We can also use a short trick to get the second-last values by modifying the base name command to something like this −
sh-3.2# echo $(basename $(dirname $PATH))
The above command will help to get the second last name of the PATH variable, which is a directory.
Output
.cargo
Similarly, we can print the third last name as well.
Command
sh-3.2# echo $(basename $(dirname $(dirname $PATH)))
Output
immukul
- Related Articles
- Get an Absolute Filename Path from a Relative Filename Path in Java
- Get an Absolute Filename Path from a Relative Filename with Path in Java
- Get filename from string path in JavaScript?
- How to get the file name from the file path in Python?
- How to get file name from a path in PHP?
- How to get left substring in MySQL from a column with file path? Display the entire file path string excluding the file name?
- Java Program to remove file information from a filename returning only its path component
- Java Program to remove path information from a filename returning only its file component
- How to get file last modified time in Java?
- Get the Full Path of a File in Linux
- Get Absolute path of a file in Java
- How to Create a New File in Linux from Bash?
- How to get the absolute path of a file using tkFileDialog(Tkinter)?
- Find last Directory or file from a given path
- Get the name of the file and path in Java
