开发者

Changing PS1 only if a certain substring isn't already in PS1 (bash)

I've got this little nifty thing in my .bashrc:

has_gitbranch() {
  if [ -e .git ]; then
    GIT_BRANCH='$(__git_ps1 "%s")'
    [ "$GIT_BRANCH" != 'master' ] && export PS1="$GIT_BRANCH$PS1"
  fi
}

venv_cd () {
   cd "$@" && has_gitbranch
}
alias cd="venv_cd"

(I didn't write it myself and can't remember where I got it from)

The problem is that if I enter a directory that is a git repo this happens:

reponamepeterbe@computername:~/directory $

That's fine but what happens if I enter that directory again (e.g cd .) then this happens:

reponamereponamepeterbe@computername:~/directory $

And again:

reponamereponamereponamepeterbe@computername:~/directory $

How can I change the bash if statement so that it doesn't prepend the git branch name if it's already in $PS1?

If it was Python I would just do this:

GIT_BRANCH = get_current_git_repo_name()
if GIT_BRANCH not in PS1: # or PS1.find(GIT_BRANCH) == -1
      PS1 = GIT_BRANCH + 开发者_如何学编程PS1


case "$PS1" in
"$GIT_BRANCH"*)
    ;;
*)
    PS1="$GIT_BRANCH$PS1"
    ;;
esac

That said, you're solving the wrong problem; I would store the basic PS1 value somewhere else and always build PS1 from that and the current repo name. Consider what will happen if you cd /some/other/repo.


I'm pretty confused why you're trying to modify PS1 on the fly. That's not necessary. Here's the tail end of mine:

PS1='.....[\!]$(__git_ps1 "(%s)")\$ '

PS1 is eval'ed by the shell whenever it's displayed, so that function does get run, and its output gets dumped in there. If you want to mess with it with some more git-fu, just wrap it in another function. If you want some flexible text somewhere else in your prompt, just embed another function similarly.

For the record, here's the example taken from git-completion.bash:

PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

That looks pretty darn close to what you're trying to achieve, except with the branch after the user, host and working directory instead of before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜