How to get the last dirname/filename in a file path argument in Bash?

LinuxOperating SystemOpen Source

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
raja
Published on 30-Jul-2021 08:33:19
Advertisements