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

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


当前回答

下面grep with regex也可以,

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

其他回答

我通常在sh脚本中使用它

SCRIPTSRC=`readlink -f "$0" || echo "$0"`
RUN_PATH=`dirname "${SCRIPTSRC}" || echo .`
echo "Running from ${RUN_PATH}"
...
cd ${RUN_PATH}/subfolder

你可以用它来自动化事情……

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

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

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

​​​​​

那么grep呢:

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

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