Sunday, 9 April 2023

Changing my WSL Bash prompt to include my current Git branch


Note: there's no real original research / thinking in this. it's just the result of me googling stuff, and arriving at a result. I'm writing it mostly so I have a record of it.

Yesterday I shifted my source code directories from my Windows file system (eg: C:\src\myapp) to using the WSL file system (eg: ~/src/myapp). See Changing where I home my source code dramatically speeds up my Windows / WSL2 / Docker environment.

Up until now I'd been doing my dev from C:, my Docker stuff in WSL, and my Git carry-on from Git Bash. Given my files are in the WSL file system now, and I have Git installed in there too, I figured I might as well ditch Git Bash and use Git directly via Bash.

The only thing I needed to do to shift to this work pattern is to update my shell prompt to reflect what branch I'm currently in, if it's a version-controlled directory.

EG, in Bash I see this:

adam@DESKTOP MINGW64 //wsl$/ubuntu/home/adam/src/SymfonyFastTrack (main)

But in Bash I just see this:

adam@DESKTOP //wsl$/ubuntu/home/adam/src/SymfonyFastTrack $

I don't need the MINGW64 in there (I don't even know what it means, nor have I ever had to care. Also: no need to pipe up and tell me), but I do need the branch to be shown the current branch I'm on if I'm in a source-controlled directory, like how Git Bash does it.

I googled about how to change the Bash prompt, and found a few helpful notes. Links to those @ the bottom of this article. The end result is setting my prompt thus:

PS1='\[\e[32m\]\u@\h\[\e[39m\]:\[\e[94m\]\w \[\e[36m\]$(__git_ps1 "(%s)")\[\e[39m\]\$ '

This renders as:

adam@DESKTOP //wsl$/ubuntu/home/adam/src/SymfonyFastTrack (main) $


  • I got almost all my guidance for this from How to show current git branch with colors in Bash prompt.
  • This goes in my ~/.bashrc file. I slung it in at the bottom.
  • PS1 is the variable containing Bash's primary prompt formatting. There's also PS0 -> PS4, but we don't need to worry about those.
  • \[\e[32m\] is an escape sequence that sets the colour for all characters thenceforth. The colour codes I'm using are:
    Green - for the user / computer name
    Light blue - for the path
    Cyan - for the branch
  • \u@\h is the Bash escape sequence for the current user and the short host name, separated by a literal @.
  • \w is the escape sequence for the current path.
  • $(__git_ps1 "(%s)") is the Git bit. __git_ps1 is a function that returns the branch, basically. How it does this is explained in those docs.

And that's it. As I said, none of this info is my own work, it's all from the references listed below. Cheers to the bods behind that lot.