简体   繁体   中英

Dynamic elements in bash PS1

I have put the following in my ~/.localsh file to customize my bash prompt when working with git.

Basically I want to get the current branch displayed in my terminal. The gitk tool shows branches with green background and black foreground, so thats what I'm trying to do.

What I have works, but when I press the up arrow on the keyboard to scroll back through previous commands it gets overwritten.

This stuff has happened to be before when you I din't end a color sequence with [\\e[0m]. Now it is happening to me because of calling getgitbranch function. I think it has something to do with the terminal not knowing how long the prompt is.

So, heres the question... How do I correctly use dynamic elements in my bash prompt and not get it hosed up when I use the up arrows?

function getgitbranch()
{
git branch | grep "^\*" | cut -c3-
}

function blabla()
{
PS1=""
PS1="$PS1\[\e[0;30m\]\[\e[42m\]\[\$(getgitbranch)\]\[\e[0;49m\]\[\e[0m\] "
PS1="$PS1\[\e[1;35m\][\[\e[0m\]"
PS1="$PS1\[\e[1;33m\]\w\[\e[0m\]"
PS1="$PS1\[\e[1;35m\]]\[\e[0m\]"
PS1="$PS1 \[\e[1;31m\]>\[\e[0m\] "
export PS1
}

Remove the \\[\\] from around the $(getgitbranch) . The characters output by that function actually occupy space on the screen so you want Bash to account for them. Using \\[\\] says don't count the characters that appear within.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM