1

正如这个问题中所解释的,我们可以获得当前工作目录的名称。但是如何获得最后一个目录名呢?

设想:

# working directory /etc/usr/abc/xyz.txt 
printf '%s\n' "${PWD##*/}" #prints abc
#i want to print usr
printf '%s\n' "%{PWD##*/-1}" #prints me whole path

建议我如何做到这一点。

提前致谢。

4

2 回答 2

7

经典的方法是:

echo $(basename $(dirname "$PWD"))

删除路径的dirname最后一个组件;basename返回剩下的最后一个组件。这具有在根目录附近工作的额外优点,其中使用${PWD##…}etc 进行变量编辑不一定有效。

于 2014-12-17T05:58:04.243 回答
4

假设您不只是basename "$(dirname "$PWD")"出于某种原因想要运行,并且您真的想为此使用扩展(请注意此处的警告)您想要使用。

# Strip the current directory component off.
tmppwd=${PWD%/*}
# Strip all leading directory components off.
echo "${tmppwd##*/}"

但是其中一个链接评论中提到的数组扩展技巧很聪明(尽管由于其他扩展属性(例如通配符等)而很棘手)。

于 2014-12-17T06:01:12.783 回答