- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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