Use Git branch name in Windows shell prompt

Set Windows shell Prompt command to include the current Git branch

Git on Windows comes with ability to open a bash shell at a directory. The prompt in the shell contains the current Git branch name. By default the prompt will consist of user name, current directory and the Git branch, example: me@mymachine /c/foo/opt/abs (sprint25)

In a Windows command shell to duplicate this you have to set it on your own, afaik.

To see what is the current Git branch in a DOS shell you can use the branch command or just list the file Git uses to store the info:

git branch -v
or
type .git/HEAD

To make the current branch obvious you can put the info in the DOS prompt. For example,

prompt $P (sprint25)

would result in a prompt as:
C:foooptabs (sprint25)

Utility
To automate this you can create a batch file that does the prompt setting, for example:

@echo off
for /F "tokens=3 delims=/" %%i in (.git/HEAD) do prompt $P (%%i)

In DOS unlike Bash or any modern shell, you cannot modify the prompt setting. However, you can add a batch file between the user and the invoked target program, git.exe.

@echo off
for /F "tokens=3 delims=/" %%i in (.git/HEAD) do prompt $P (%%i)

"Program Files\Git\bin\git.exe" %*

This has a slight problem with bare or separate-git-dir type repositories; you’ll see the “The system cannot find the file .git/HEAD.” warning and the prompting will not be set.

Why change prompt?
Reduce the possibility of human error. However, in this DOS approach, there is no way to make the prompt dynamic and update on changes to current branch. Or is there? Perhaps a hook script can be added in Git or there is some other means?

Disclaimer: I’m a Git newbie, so the above is probably a newbie non-elegance. I looked in git-config and did not see a solution.

Updates

Further reading

  1. Using Git with Windows Powershell
  2. How can I display my current git branch name in my PowerShell prompt?
  3. Using Git (and everything else) through PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *