在Bash脚本中获取当前目录名称(无完整路径) [英] Get current directory name (without full path) in a Bash script

查看:386
本文介绍了在Bash脚本中获取当前目录名称(无完整路径)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在bash脚本中仅获取当前的工作目录名称,或者甚至更好地仅是终端命令.

How would I get just the current working directory name in a bash script, or even better, just a terminal command.

pwd给出当前工作目录的完整路径,例如/opt/local/bin,但我只想要bin

pwd gives the full path of the current working directory, e.g. /opt/local/bin but I only want bin

推荐答案

不需要基本名称,尤其不需要运行pwd的子外壳(其中添加了额外且昂贵的fork操作);外壳程序可以使用参数扩展在内部完成此操作:

No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:

result=${PWD##*/}          # to assign to a variable

printf '%s\n' "${PWD##*/}" # to print to stdout
                           # ...more robust than echo for unusual names
                           #    (consider a directory named -e or -n)

printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input
                           # ...useful to make hidden characters readable.


请注意,如果您在其他情况下(不是PWD,而是其他具有目录名称的变量)应用此技术,则可能需要修剪任何斜杠.以下内容使用了bash的 extglob支持,即使有多个斜杠也可以使用:


Note that if you're applying this technique in other circumstances (not PWD, but some other variable holding a directory name), you might need to trim any trailing slashes. The below uses bash's extglob support to work even with multiple trailing slashes:

dirname=/path/to/somewhere//
shopt -s extglob           # enable +(...) glob syntax
result=${dirname%%+(/)}    # trim however many trailing slashes exist
result=${result##*/}       # remove everything before the last / that still remains
printf '%s\n' "$result"

或者,不包含extglob:

dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}"                  # remove everything before the last /

这篇关于在Bash脚本中获取当前目录名称(无完整路径)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆