Bash 提示 (PS1) 未按预期工作

Bash prompt (PS1) not working as intended

这是我的.bashrc文件,我稍后会解释我的问题。

#!/usr/bin/env bash

PS_LINE=`printf -- '  %.0s' {1..200}`

function parse_git_branch {
    PS_BRANCH=''
    PS_FILL=${PS_LINE:0:$COLUMNS}

    if [ -d .svn ] ; then
        PS_BRANCH="(svn r$(svn info|awk '/Revision/{print }'))"
        return

    elif [ -f _FOSSIL_ -o -f .fslckout ] ; then
        PS_BRANCH="(fossil $(fossil status|awk '/tags/{print }')) "
        return

    elif [ -d .hg ] ; then
        PS_BRANCH="(hg $(hg branch))"
        return
    
    fi

    ref=$(git symbolic-ref HEAD 2> /dev/null) || return
    PS_BRANCH="(git ${ref#refs/heads/}) "
}

PROMPT_COMMAND=parse_git_branch

PS_INFO="$GREEN$USER$RESET@$GREEN$HOSTNAME$RESET:$BLUE\w"
PS_VCS="$YELLOW$PS_BRANCH"
PS_TIME="\[3[$((COLUMNS-10))G\] $RED[\t]"

export PS1="${PS_FILL}\[3[0G\]${PS_INFO} ${PS_GIT}${PS_TIME}\n${RESET}$ "

好的。所以我想要的是我当前目录和时间之间有一个空行(like this). As you can see, that works fine but when I restart my shell (not resource my .bashrc), it looks like this(它们之间没有空格)

编辑

根据@chepner 的回答,我得到了 this

更新代码:

function parse_git_branch {
    PS_BRANCH=''
    PS_FILL=${PS_LINE:0:$COLUMNS}

    if [ -d .svn ] ; then
        PS_BRANCH="(svn r$(svn info|awk '/Revision/{print }'))"
        return

    elif [ -f _FOSSIL_ -o -f .fslckout ] ; then
        PS_BRANCH="(fossil $(fossil status|awk '/tags/{print }')) "
        return

    elif [ -d .hg ] ; then
        PS_BRANCH="(hg $(hg branch))"
        return
    
    fi

    ref=$(git symbolic-ref HEAD 2> /dev/null) || return
    PS_BRANCH="(git ${ref#refs/heads/}) "
}

function set_prompt {
    PS_INFO="$GREEN$USER$RESET@$GREEN$HOSTNAME$RESET:$BLUE\w"
    PS_VCS="$YELLOW$PS_BRANCH"
    PS_TIME="\[3[$((COLUMNS-10))G\] $RED[\t]"
}

PROMPT_COMMAND=set_prompt

export PS1="${PS_FILL}\[3[0G\]${PS_INFO} ${PS_GIT}${PS_TIME}\n${RESET}$ "

显然,终端 window 中的实际列数仅在发出第一个提示后才分配给 COLUMNS 变量 - 我可以重现这一点。 (这可能取决于处理 window 调整大小信号的时间。)一个不太好但有效的补救措施是延迟 .bashrc - 对我来说,sleep .2 有效。另一种方法是,如果预先知道打开终端的列数,则将 COLUMNS 设置为该值。