基于文件系统中的位置的Shell提示符

我必须在根文件系统下的三个主目录下工作 – home / username,project和scratch。 我想我的shell提示符显示我在哪些顶级目录。

这是我正在做的事情:

top_level_dir () { if [[ "${PWD}" == *home* ]] then echo "home"; elif [[ "${PWD}" == *scratch* ]] then echo "scratch"; elif [[ "${PWD}" == *project* ]] then echo "project"; fi } 

然后,我将PS1导出为:

 export PS1='$(top_level_dir) : ' 

不幸的是,这不是我想要的。 我home :为我的提示,当我在我的家目录,但如果我切换到草稿或项目,然后提示不会改变。 我不明白bash脚本很好,所以我将不胜感激任何帮助来纠正我的代码。

每次更改工作目录时,都可以挂接到cd来更改提示。 我经常问自己如何挂钩到cd但我认为我现在找到了一个解决方案。 把这个加到你的~/.bashrc怎么样?

 # # Wrapper function that is called if cd is invoked # by the current shell # function cd { # call builtin cd. change to the new directory builtin cd $@ # call a hook function that can use the new working directory # to decide what to do color_prompt } # # Changes the color of the prompt depending # on the current working directory # function color_prompt { pwd=$(pwd) if [[ "$pwd/" =~ ^/home/ ]] ; then PS1='\[\033[01;32m\]\u@\h:\w\[\033[00m\]\$ ' elif [[ "$pwd/" =~ ^/etc/ ]] ; then PS1='\[\033[01;34m\]\u@\h:\w\[\033[00m\]\$ ' elif [[ "$pwd/" =~ ^/tmp/ ]] ; then PS1='\[\033[01;33m\]\u@\h:\w\[\033[00m\]\$ ' else PS1='\u@\h:\w\\$ ' fi export PS1 } # checking directory and setting prompt on shell startup color_prompt 

请尝试使用此方法,并告诉我们它是如何工作的,例如您的主目录,项目或暂存目录以及其他目录中的提示如何更改。 告诉我们你也看到了什么错误信息。 问题在于它。

告诉我你是如何运行的,如果是通过脚本,通过直接执行,或者通过启动脚本,如〜/ .bashrc。

 top_level_dir () { __DIR=$PWD case "$__DIR" in *home*) echo home ;; *scratch*) echo scratch ;; *project*) echo project ;; *) echo "$__DIR" ;; esac } export PS1='$(top_level_dir) : ' export -f top_level_dir 

如果不起作用,请尝试将__DIR=$PWD更改为__DIR=$(pwd)并告诉我们是否也有帮助。 我也想确认你是否真的在运行bash 。 请注意, sh有很多变种,如bashzshkshdash ,缺省安装和使用的变种取决于每个系统。 要确认你正在使用Bash,请echo "$BASH_VERSION" ,看它是否显示一条消息。

您还应该确保您正在运行export PS1='$(top_level_dir) : '使用单引号而不使用双引号: export PS1="$(top_level_dir) : "