views:

271

answers:

3

How do I extract the last directory of a pwd output? I don't want to use any knowledge of how many levels there are in the directory structure. If I wanted to use that, I could do something like:

> pwd
/home/kiki/dev/my_project
> pwd | cut -d'/' -f5
my_project

But I want to use a command that works regardless of where I am in the directory structure. I assume there is a simple command to do this using awk or sed.

+4  A: 

Are you looking for basename or dirname?

Something like

basename `pwd`

should be what you want to know.

If you insist on using sed, you could also use

pwd | sed 's#.*/##'
mihi
Nice, that works. Thanks!
Siou
Or, more likely `endpath=$(basename $(pwd))`.
Jonathan Leffler
Missing quotes around "$(pwd)". Try this without the quotes: mkdir "ab b"; cd "ab b" endpath=$(basename "$(pwd)")
Mark Edgar
+3  A: 

If you want to do it completely within a bash script without running any external binaries, ${PWD##*/} should work.

Teddy
Up to a point...if you arrived at the directory via a symlink with a different name, then the $PWD value will be different from the value produced by /bin/pwd or /usr/bin/pwd (which is distinct from the pwd built-in).
Jonathan Leffler
@Jonathan Leffler: The questioner used the pwd built-in, so I feel it was appropriate to use $PWD.
Teddy
A: 

Using awk:

pwd | awk -F/ '{print $NF}'
chrispix