我如何在bash脚本中检索当前工作目录/文件夹名称,或者更好的是,仅仅是一个终端命令。

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


当前回答

对于像我这样的骑手来说

find $PWD -maxdepth 0 -printf "%f\n"

其他回答

$ echo "${PWD##*/}"

​​​​​

Use:

basename "$PWD"

OR

IFS=/ 
var=($PWD)
echo ${var[-1]} 

将内部文件名分隔符(IFS)调回空格。

IFS= 

在IFS后面有一个空格。

如果您只想看到bash提示符区域中的当前目录,可以在~中编辑.bashrc文件。在行中将\w改为\w:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

执行source ~/。Bashrc,它只会在提示区域显示目录名。

裁判:https://superuser.com/questions/60555/show-only-current-directory-name-not-full-path-on-bash-prompt

有很多方法可以做到这一点,我特别喜欢Charles的方法,因为它避免了一个新的过程,但在知道这一点之前,我用awk解决了它

pwd | awk -F/ '{print $NF}'

对于像我这样的骑手来说

find $PWD -maxdepth 0 -printf "%f\n"