Take the last part of the folder path in shell

2019-04-03 07:52发布

问题:

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:

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

basename "$PWD"


回答2:

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



回答3:

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)



回答4:

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

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


回答5:

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

basename $(pwd);


回答6:

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

basename "$PWD"
echo "$__"


标签: linux bash shell