4

我必须在根文件系统下的三个主要目录中工作——主目录/用户名、项目和临时目录。我希望我的 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 脚本,所以如果能帮助我更正我的代码,我将不胜感激。

4

2 回答 2

7

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
于 2013-08-15T00:21:51.567 回答
1

请改用此方法并告诉我们它是如何工作的,例如您的主目录、项目或临时目录以及除这些之外的其他目录中的提示如何更改。告诉我们您还看到了哪些错误消息。问题就在其中。

告诉我你是如何运行它的,是通过脚本、直接执行还是通过像 ~/.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)并告诉我们它是否也有帮助。我还想确认您是否真的在跑步bashsh请注意, like bashzshksh和有许多变体,dash默认安装和使用的变体取决于每个系统。要确认您正在使用 Bash,请执行echo "$BASH_VERSION"并查看它是否显示一条消息。

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

于 2013-08-15T07:38:12.163 回答