36

If you type pwd you get something like:

/home/username/Desctop/myfolder/

How to take the last part? The myfolder path.

This must be simple but I couldn't find easy solution in shell. I know how to take care of this in java but not in shell.

thanks

1
  • I don't think that's correct: the output of pwd does not contain a trailing /.
    – Jens
    Commented Aug 20, 2015 at 8:19

6 Answers 6

37

You're right--it's a quick command:

basename "$PWD"
1
  • 1
    That's at least one useless expensive fork. What about using $PWD?
    – Jens
    Commented Jun 5, 2014 at 6:24
15

Using basename $(pwd) are two useless and expensive forks.

echo "${PWD##*/}"

should do the trick completely in the shell without expensive forks (snag: for the root directory this is the empty string).

1
  • 2
    Only thing is that the last / gets removed in basename (may not a pply with $PWD but in other custom paths it may. Still I'd choose this method over it. Another ${VAR%/} (before) is not difficult. +1 for the answer, and also mentioning the word expensive.
    – konsolebox
    Commented Jun 5, 2014 at 6:29
2

In Linux, there are a pair of commands, dirname and basename. dirname extracts all but the last part of a path, and basename extracts just the last part of a path.

In this case, using basename will do what you want:

basename $(pwd)

1

You can use basename for that, provided the last part is indeed a directory component (not a file):

$ basename /home/username/Desctop/myfolder/
myfolder
1

To extract the last part of a path, try using basename...

basename $(pwd);
1
  • The best answer so far, It works in my mac but Im unsure about what linux distros this cmd is available.
    – bmaggi
    Commented Apr 13, 2022 at 21:01
0
function basename {
    shopt -s extglob
    __=${1%%+(/)}
    [[ -z $__ ]] && __=/ || __=${__##*/}
}

basename "$PWD"
echo "$__"

Your Answer

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

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