48

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.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Siou
  • 497
  • 1
  • 5
  • 9

4 Answers4

74

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
  • 6,507
  • 1
  • 38
  • 48
25

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

Teddy
  • 6,013
  • 3
  • 26
  • 38
  • 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 Nov 16 '09 at 20:40
  • @Jonathan Leffler: The questioner used the pwd built-in, so I feel it was appropriate to use $PWD. – Teddy Nov 17 '09 at 20:43
  • Can you please help me understand what the ##*/ are doing exactly? Thank you. – raphael75 Oct 23 '18 at 19:11
  • 3
    I found it it's command substitution: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html – raphael75 Oct 23 '18 at 19:29
4

Using awk:

pwd | awk -F/ '{print $NF}'
Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
4

Should work for you: pwd | rev | cut -f1 -d'/' - | rev

Reference: https://stackoverflow.com/a/31728689/663058

Community
  • 1
  • 1
CenterOrbit
  • 6,446
  • 1
  • 28
  • 34