Linux 取shell中文件夹路径的最后一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10654135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:23:13  来源:igfitidea点击:

Take the last part of the folder path in shell

linuxbashshell

提问by Lukap

If you type pwd you get something like:

如果你输入 pwd 你会得到类似的东西:

/home/username/Desctop/myfolder/

/home/username/Desctop/myfolder/

How to take the last part? The myfolderpath.

最后一部分怎么打?该myfolder路径。

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.

这一定很简单,但我在 shell 中找不到简单的解决方案。我知道如何在 java 中处理这个问题,但在 shell 中不知道如何处理。

thanks

谢谢

采纳答案by andyras

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

你是对的——这是一个快速命令:

basename "$PWD"

回答by Eduardo Ivanec

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

您可以使用basename它,前提是最后一部分确实是目录组件(不是文件):

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

回答by alex

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

要提取路径的最后一部分,请尝试使用basename...

basename $(pwd);

回答by octopusgrabbus

In Linux, there are a pair of commands, dirnameand basename. dirnameextracts all but the last part of a path, and basenameextracts just the last part of a path.

在 Linux 中,有一对命令,dirnamebasename. dirname提取除路径最后一部分之外的所有内容,并basename仅提取路径的最后一部分。

In this case, using basenamewill do what you want:

在这种情况下, usingbasename将执行您想要的操作:

basename $(pwd)

basename $(pwd)

回答by Jens

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

使用的basename $(pwd)两个无用且昂贵的叉子

echo ${PWD##*/}

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

应该完全在 shell 中完成这个技巧,而无需昂贵的分叉(障碍:对于根目录,这是空字符串)。

回答by konsolebox

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

basename "$PWD"
echo "$__"