1

所以我有一个脚本.bashrc用于自定义我的提示(见下文)。

function git_unpushed {
    brinfo=$(git branch -v)
    if [[ $brinfo =~ ("[ahead "([[:digit:]]*)]) ]]
    then
        echo "Not Pushed: ${BASH_REMATCH[2]}"
    fi
}

function git_untracked {
    untracked=$(git clean --dry-run | wc -l)
    if [ $untracked -gt 0 ]
    then
        echo "Untracked: "$untracked
    fi
}

export PS1="\
$(
    # last_result=$?
    uid="$(id -u)"
    host="\[\e[97m\]\H"
    path="\[\e[94m\]\w"
    
    # If root
    if [ "$uid" = "0" ];
    then
        user="\[\e[95m\]\u"
        symbol="\[\e[97m\]#"
    else
        # If not root
        user="\[\e[96m\]\u"
        symbol="\[\e[97m\]\$"
    fi
    
    # If Git Repo
    if [ -d './.git' ];
    then
        unpushed=$(git_unpushed)
        untracked=$(git_untracked)
        branch=$(__git_ps1)
        status=$(git diff --shortstat)
        second_line="hi"
    else
        second_line=$path
    fi
    
    echo "\[\e[1m\]$user@$host\n$second_line\n$symbol: \[\e[0m\]"
)"

我的问题:为什么每当我cd到 git repo 时路径都不会被替换?(如果我在 repo 中启动 bash 提示符,它会这样做”

我正在使用 Ubuntu 14.04


更新:

经过大量工作使其恰到好处,他是我的结果:Custom $PS1

感谢所有帮助过的人!

4

1 回答 1

4

编辑:

正如@EtanReisner指出的那样,您的代码应该通过将您的命令替换用单引号括起来,为所有用户按预期工作。

    export PS1='\
    $(
        # last_result=$?
        uid="$(id -u)"
        host="\[\e[97m\]\H"
        path="\[\e[94m\]\w"

        # If root
        if [ "$uid" = "0" ];
        then
            user="\[\e[95m\]\u"
            symbol="\[\e[97m\]#"
        else
            # If not root
            user="\[\e[96m\]\u"
            symbol="\[\e[97m\]\$"
        fi

        # If Git Repo
        if [ -d "./.git" ];
        then
            unpushed=$(git_unpushed)
            untracked=$(git_untracked)
            branch=$(__git_ps1)
            status=$(git diff --shortstat)
            second_line="hi"
        else
            second_line=$path
        fi

        echo "\[\e[1m\]$user@$host\n$second_line\n$symbol: \[\e[0m\]"
    )'

老答案:

这是因为你想要发生的只是每次你的 ~/.bashrc 被获取时运行。要让它在您执行的每个命令后运行,您可以创建一个函数并将环境变量PROMPT_COMMAND设置为该函数。

尝试这个:

new_ps1 (){
    export PS1="\
    $(
        # last_result=$?
        uid="$(id -u)"
        host="\[\e[97m\]\H"
        path="\[\e[94m\]\w"

        # If root
        if [ "$uid" = "0" ];
        then
            user="\[\e[95m\]\u"
            symbol="\[\e[97m\]#"
        else
            # If not root
            user="\[\e[96m\]\u"
            symbol="\[\e[97m\]\$"
        fi

        # If Git Repo
        if [ -d './.git' ];
        then
            unpushed=$(git_unpushed)
            untracked=$(git_untracked)
            branch=$(__git_ps1)
            status=$(git diff --shortstat)
            second_line="hi"
        else
            second_line=$path
        fi

        echo "\[\e[1m\]$user@$host\n$second_line\n$symbol: \[\e[0m\]"
    )"
}
PROMPT_COMMAND="new_ps1"
于 2014-08-13T01:27:33.383 回答