Skip to content

Instantly share code, notes, and snippets.

@erikmd
Last active September 8, 2024 12:50
Show Gist options
  • Save erikmd/20b6c5305424058002580303d05226e0 to your computer and use it in GitHub Desktop.
Save erikmd/20b6c5305424058002580303d05226e0 to your computer and use it in GitHub Desktop.
How to setup some GIt prompt in Bash or Zsh

Howto: Setup a Git prompt for Bash or Zsh

Disclaimer

This mini-tutorial describes a dangerous step (dowload a third-party bash script and execute/source it).

In a similar case, be always careful to:

  • only do this from trusted sources (here, from a released tag in https://github.com/git/git)
  • and inspect the script beforehand! (i.e., always avoid any blind curl … | bash command)

This tutorial is only applicable for GNU/Linux and macOS, given Git BASH for Windows already comes with a builtin Git prompt.

Installation steps

git --version
version=$(git --version | cut -d ' ' -f 3)
curl -L -o ~/.git-prompt.sh https://github.com/git/git/raw/v$version/contrib/completion/git-prompt.sh
head ~/.git-prompt.sh  # only to display the heading doc; doesn't preclude from a thorough inspection
chmod a-w ~/.git-prompt.sh

Using bash (under GNU/Linux)

Append the following code at the end of ~/.bashrc:

################ ADD IN THE END ################
if [ -f ~/.git-prompt.sh ]; then
    . ~/.git-prompt.sh
    # export GIT_PS1_SHOWUNTRACKEDFILES="true"
    export GIT_PS1_SHOWDIRTYSTATE="true"
    export GIT_PS1_SHOWUPSTREAM="verbose git" # name
    export GIT_PS1_DESCRIBE_STYLE="branch"
    # Bash: initially: PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
    # better: let us use substring substitution.
    PS1="${PS1/\\\$/\$(__git_ps1 \" (%s)\")\\\$}"
    # alternatively:
    # PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
fi

Using zsh (under macOS or so)

Append the following code at the end of ~/.zshrc:

################ ADD IN THE END ################
if [ -f ~/.git-prompt.sh ]; then
    . ~/.git-prompt.sh
    # export GIT_PS1_SHOWUNTRACKEDFILES="true"
    export GIT_PS1_SHOWDIRTYSTATE="true"
    export GIT_PS1_SHOWUPSTREAM="verbose" # "verbose git" # name
    export GIT_PS1_DESCRIBE_STYLE="branch"
    # Zsh: initially: PS1='%n@%m %1~ %# '
    # better: let us use substring substitution.
    setopt PROMPT_SUBST
    PS1="${PS1/\%#/\$(__git_ps1 \"(%s) \")%#}"
    # alternatively:
    # PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment