linux – BASH command to get the name of the n-th directory in the path


You need to find out the name of the directory located above the current one, then even higher, etc. in BASH

For example, there is a directory:

/ home / Ochen / Glupiy / Vopros

I need to get a name: Glupiy

Then get the name even more top DIR: Ochen


If for the current directory ( Vopros ) my BASH command is

pwd | grep -o '[^/]*$'

was a square wheel, then the command for the directory that is higher ( Glupiy ) can be called

pwd | grep -o [^/]* | sed -e '$!{h;d;}' -ex

For the directory, which is even higher, I have not come up with anything 🙂

I need to somehow compose such a BASH command, with which I could pull the name of the current, upper, which is even higher, etc., directory.

If it is impossible to compose a more or less universal command, then throw at me at least a command to get the name DIR 2 levels higher.

For example for: / home / Ochen / Glupiy / Vopros

get name: Ochen


you can use the basename and dirname programs:

  • basename extracts the last part from the passed path
  • dirname "cuts" the last part from the given path, leaving everything else

$ cd /home/Ochen/Glupiy/Vopros
$ basename $(pwd)
$ dirname $(pwd)
$ basename $(dirname $(pwd))
$ basename $(dirname $(dirname $(pwd)))
Scroll to Top