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

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


当前回答

只使用:

pwd | xargs basename

or

basename "`pwd`"

其他回答

这个帖子很棒!这里还有一种味道:

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

以下命令将在bash脚本中打印当前工作目录。

pushd .
CURRENT_DIR="`cd $1; pwd`"
popd
echo $CURRENT_DIR

那么grep呢:

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

下面grep with regex也可以,

>pwd | grep -o "\w*-*$"

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