49

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.

1
  • What if your working directory is / ?
    – Mark Edgar
    Nov 16, 2009 at 21:17

4 Answers 4

76

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#.*/##'
2
  • 7
    Or, more likely endpath=$(basename $(pwd)). Nov 16, 2009 at 20:39
  • 4
    Missing quotes around "$(pwd)". Try this without the quotes: mkdir "ab b"; cd "ab b" endpath=$(basename "$(pwd)")
    – Mark Edgar
    Nov 16, 2009 at 21:14
26

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

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

Using awk:

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

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

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

2
  • Not sure why this was down-voted. I'm quite fond of this method. If there's a good reason, I'd like to hear it. Feb 22, 2018 at 21:52
  • I don't see what's wrong with this either. Works for my use case.
    – mixedbag99
    Apr 6, 2018 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.