TIL: How to speed up git status in your Bash prompt

Tom Deneire
3 min readJan 13, 2024
Photo by Roman Synkevych on Unsplash

Bash prompt

A while ago I wrote about how to customize your terminal prompt with Bash only:

In order to get your git status displayed in the prompt, I turned to the official git-prompt.sh shell script, which you can find here:

Speeding things up

However, after a while, and especially on large repos, I started noticing that this slowed down my terminal considerably. Granted that git status is an expensive command as it is, after having a look at git-prompt.sh — which is about 500 lines of code — I found that there was still some room to speed things up.

Of course, the exact definition of what git status information is relevant in a terminal prompt, will differ from user to user. For me, though, I found that the essence is:

  • local branch name
  • upstream branch name
  • comparison between local and upstream
  • summary of differences

Solution

If that’s all we’re interested in, we don’t need a 500 line Bash script. Here’s the much shorter and therefore faster code I came up with (kindly assisted by Bing Copilot, I might add, who was an excellent awk sparring partner!):

git_status() {
MYSTATUS=$(git status -sb --untracked-files=no --ignore-submodules 2> /dev/null | awk '
/^##/ { branch = substr($0, 4) }
/^[[:space:]]+[A-Z]/ { count += gsub(/[[:upper:]]/, "", $1) }
END { if (count > 0) printf("%s *%d", branch, count); else printf("%s", branch)}
')
if [ "$MYSTATUS" != "" ]; then
echo " ($MYSTATUS)"
fi
}

--

--