我如何在bash脚本中检索当前工作目录/文件夹名称,或者更好的是,仅仅是一个终端命令。
pwd给出了当前工作目录的完整路径,例如/opt/local/bin,但我只想要bin。
我如何在bash脚本中检索当前工作目录/文件夹名称,或者更好的是,仅仅是一个终端命令。
pwd给出了当前工作目录的完整路径,例如/opt/local/bin,但我只想要bin。
当前回答
不需要basename,特别是不需要运行pwd的子shell(这会增加额外且昂贵的fork操作);shell可以在内部使用参数展开:
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支持,即使使用多个尾随斜杠也能正常工作:
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
其他回答
echo "$PWD" | sed 's!.*/!!'
如果您正在使用Bourne shell或${pwd# #*/}不可用。
basename $(pwd)
or
echo "$(basename $(pwd))"
我喜欢选择的答案(Charles Duffy),但如果您在符号链接目录中,并且想要目标目录的名称,请小心。不幸的是,我不认为它可以在一个参数展开表达式中完成,也许我错了。这应该可以工作:
target_PWD=$(readlink -f .)
echo ${target_PWD##*/}
为了验证这一点,我们做了一个实验:
cd foo
ln -s . bar
echo ${PWD##*/}
报告“酒吧”
目录名
显示路径的主目录(不触发/usr/bin/dirname的fork-exec命令):
echo ${target_PWD%/*}
这将转换foo/bar/baz -> foo/bar
使用basename程序。对于你的情况:
% basename "$PWD"
bin
我强烈倾向于使用gbasename,它是GNU coreutils的一部分。