Sometimes, we want to show current git branch in Bash prompt. git symbolic-ref --short -q HEAD
is too slow, especially in WSL. Here is a pure Bash version to print git branch.
function _get_git_branch() {
local _head_file _head
local _dir="$PWD"
while [[ -n "$_dir" ]]; do
_head_file="$_dir/.git/HEAD"
if [[ -f "$_dir/.git" ]]; then
read -r _head_file < "$_dir/.git" && _head_file="$_dir/${_head_file#gitdir: }/HEAD"
fi
[[ -e "$_head_file" ]] && break
_dir="${_dir%/*}"
done
if [[ -e "$_head_file" ]]; then
read -r _head < "$_head_file" || return
case "$_head" in
ref:*) printf "${_head#ref: refs/heads/}" ;;
"") ;;
# HEAD detached
*) printf "${_head:0:9}" ;;
esac
return 0
fi
return 1
}
It is tremendously faster than git command (1ms vs 74ms). Tested on Ubuntu 20.04 (WSL1),
david@Ubuntu:/m/c/U/b/R/T/E/M/T/teeProxyConsole[develop]$ time git symbolic-ref --short -q HEAD
develop
real 0m0.074s
user 0m0.000s
sys 0m0.016s
david@Ubuntu:/m/c/U/b/R/T/E/M/T/teeProxyConsole[develop]$ time _get_git_branch
develop
real 0m0.001s
user 0m0.000s
sys 0m0.016s
@dtucny because git command works poorly on Windows with lots of small files (you can try
git status
). This is also my pain point on Win. My version is just to read the HEAD file and get the branch name from file.Glad to hear it helps :)