Lukap
Lukap

Reputation: 31963

Take the last part of the folder path in shell

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

Upvotes: 36

Views: 26606

Answers (6)

Jens
Jens

Reputation: 72737

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).

Upvotes: 16

andyras
andyras

Reputation: 15930

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

basename "$PWD"

Upvotes: 37

konsolebox
konsolebox

Reputation: 75578

function basename {
    shopt -s extglob
    __=${1%%+(/)}
    [[ -z $__ ]] && __=/ || __=${__##*/}
}

basename "$PWD"
echo "$__"

Upvotes: 0

alex
alex

Reputation: 490509

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

basename $(pwd);

Upvotes: 1

octopusgrabbus
octopusgrabbus

Reputation: 10695

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)

Upvotes: 2

Eduardo Ivanec
Eduardo Ivanec

Reputation: 11862

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

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

Upvotes: 1

Related Questions