No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation );
(不需要基名,特别是不需要运行pwd的子shell(它增加了额外且昂贵的fork操作 );)
the shell can do this internally using parameter expansion : (Shell可以使用参数扩展在内部执行此操作:)
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.
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.
(请注意,如果在其他情况下(不是PWD
,而是其他具有目录名的变量)应用此技术,则可能需要修剪任何斜杠。)
The below uses bash's extglob support to work even with multiple trailing slashes: (下面使用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
printf '%s
' "$result"
Alternatively, without extglob
:
(或者,不使用extglob
:)
dirname="/path/to/somewhere//"
result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trim
result="${result##*/}" # remove everything before the last /
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…