Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

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

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

(我如何在bash脚本中仅获得当前的工作目录名称,甚至更好,仅是终端命令。)

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

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

  ask by Derek Dahmer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 /

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...