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
That said, you’re solving the wrong problem; I would store the basic
PS1value somewhere else and always buildPS1from that and the current repo name. Consider what will happen if youcd /some/other/repo.