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

时间:2013-08-14 23:20:14

标签: linux bash shell unix command-prompt

我必须在根文件系统下的三个主目录中工作 - 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脚本,所以我很感激任何帮助来纠正我的代码。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)并告诉我们是否也有帮助。我还想确认你是否真的在运行bash。请注意,shbashzshkshdash的变体很多,默认情况下安装和使用的变体取决于每个系统。要确认您使用的是Bash,请执行echo "$BASH_VERSION"并查看是否显示消息。

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