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

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


当前回答

echo "$PWD" | sed 's!.*/!!'

如果您正在使用Bourne shell或${pwd# #*/}不可用。

其他回答

echo "$PWD" | sed 's!.*/!!'

如果您正在使用Bourne shell或${pwd# #*/}不可用。

basname示例的替代方案

pwd | grep -o "[^/]*$"

OR

pwd | ack -o "[^/]+$"

我的shell没有附带basename包,如果有办法的话,我倾向于避免下载包。

如果您只想看到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

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

​​​​​

可以使用basename实用程序从string中删除任何以/结尾的前缀和后缀(如果存在于string中),并打印 标准输出的结果。

$basename <path-of-directory>