Skip to content

Instantly share code, notes, and snippets.

@juliyvchirkov
Last active June 23, 2022 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliyvchirkov/883a050c34e23f4b4fba6ecaeb050c3b to your computer and use it in GitHub Desktop.
Save juliyvchirkov/883a050c34e23f4b4fba6ecaeb050c3b to your computer and use it in GitHub Desktop.
bash: simplified custom function __git_ps1 to display current branch or tag name in git repo
#!/usr/bin/env bash
#
# If one is missing the original *__git_ps1* function from @git/git package, this wrapper can be utilized as
# temporary solution. Just like the original, it prints current branch name like *main*, *dev* etc. or tags
# like *v1.4.0*, or nothing, if current directory is outside of any git tree
#
# @see https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
#
# Significantly updated 06/18/2022
#
# To get the function working everywhere in bash properly one have to add the code below to */etc/bash.bashrc* or local
# *~/.bashrc*. The final command *export -f __git_ps1* will make the wrapper available even after *sudo -i*
declare -F | grep __git_ps1 &>/dev/null || {
__git_ps1() {
local branch="$(git symbolic-ref -q --short HEAD 2>/dev/null)"
local template="${*}"
[ $? -eq 0 ] && [ -n "${branch}" ] || {
branch="$(git describe --tags --exact-match 2>/dev/null)"
[ $? -eq 0 ] && [ -n "${branch}" ] || return
branch="(${branch})"
}
[ -z "${template}" ] && template=" %s" || {
[[ "${template}" = *%s* ]] || template+=" %s"
}
printf "${template}" "${branch}"
}
export -f __git_ps1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment