Take the last part of the folder path in shell

2019-04-03 07:45发布

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

标签: linux bash shell
6条回答
别忘想泡老子
2楼-- · 2019-04-03 08:10

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

$ basename /home/username/Desctop/myfolder/
myfolder
查看更多
仙女界的扛把子
3楼-- · 2019-04-03 08:13

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

查看更多
4楼-- · 2019-04-03 08:15
function basename {
    shopt -s extglob
    __=${1%%+(/)}
    [[ -z $__ ]] && __=/ || __=${__##*/}
}

basename "$PWD"
echo "$__"
查看更多
来,给爷笑一个
5楼-- · 2019-04-03 08:20

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

basename $(pwd);
查看更多
我只想做你的唯一
6楼-- · 2019-04-03 08:24

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

basename "$PWD"
查看更多
Melony?
7楼-- · 2019-04-03 08:32

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)

查看更多
登录 后发表回答