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

查看:37
本文介绍了在 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

推荐答案

不需要 basename,尤其不需要运行 pwd 的子shell(增加了一个额外的、昂贵的分叉操作);shell 可以在内部使用 参数扩展:

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
' "${PWD##*/}" # to print to stdout
                           # ...more robust than echo for unusual names
                           #    (consider a directory named -e or -n)

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

<小时>

请注意,如果您在其他情况下应用此技术(不是 PWD,而是其他一些保存目录名称的变量),您可能需要修剪任何尾部斜杠.下面使用 bash 的 extglob support 来处理多个斜杠:


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
' "$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天全站免登陆