gpt4 book ai didi

bash - 获取当前目录或文件夹名称(没有完整路径)

转载 作者:行者123 更新时间:2023-11-29 08:36:48 33 4
gpt4 key购买 nike

我怎样才能在 bash 脚本中检索当前工作目录/文件夹名称,或者甚至更好,只是一个终端命令。

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

最佳答案

不需要基本名称,尤其不需要运行 pwd 的子 shell(adds an extra, and expensive, fork operation); shell 可以使用 parameter expansion 在内部执行此操作:

result=${PWD##*/}          # to assign to a variable
result=${result:-/} # to correct for the case where PWD=/

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 support即使有多个尾部斜杠也能工作:

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
result=${result:-/} # correct for dirname=/ case
printf '%s\n' "$result"

或者,没有 extglob:

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

关于bash - 获取当前目录或文件夹名称(没有完整路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1371261/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com