How to make git show information in your bash prompt

29.07.2020 | Johannes Kastl in howto

What the prompt?

Usually, you won’t even notice your prompt, as you see it after every command you execute, in each shell you start. The only thing most people notice is that root seems to have a different prompt.

Depending on your distribution, your prompt will look like this:

Or maybe like this:

root’s prompt might look like this:

What most people do not know: You can customize that prompt. Simply by setting the variable PS1 how you want it to be…

Showing git information in the bash prompt

In reality, the PS1 variable looks a little different, but your bash fills in the proper information before showing the prompt

or

Use the example file to set the prompt. Add the file content to your local ~/.bashrc (or ~/.profile or ~/.bash_profile, as briefly discussed in the last post).

We start of by defining a color, as this makes the code a lot easier to read (unless you prefer [\e[01;32m\] instead of ${GREEN}…).

Then we need to source the file containing the code that does all the hard work. After that, we decide to only show the git prompt in git repos (makes sense, doesn’t it?). And then, finally we build our own prompt:

This then shows the following prompt:

In case of modified files a asterisk * is shown after master:

Once the changed file is being added to the index, this turns into a plus sign +:

Customizing the git prompt

There are two things I always add when using a git prompt: showing local modifications, staged files or deletions. And showing whether or not stashes exist. The example file contains the two stanzas that take care of this:

    ##################################################################################
    # Show git state (modified files, ...) in prompt
    #
    export GIT_PS1_SHOWDIRTYSTATE=1

    ##################################################################################
    # Show git stash state in prompt
    #
    export GIT_PS1_SHOWSTASHSTATE=1

There are many things you can do, why not read the excellent documentation? Oh wait, this is pretty short, why not look into the files themselves?

Have fun!

Example files

Johannes Kastl
Johannes Kastl
Johannes is a Linux trainer and consultant and has been with B1 Systems since 2017. His topics include configuration management (Ansible, Salt, Chef, Puppet), version control (git), Infrastructure as Code (Terraform) and automation (Jenkins) as well as testing (Inspec, anyone?). At daytime he works as a sysadmin and fixes problems, at night he tries new technologies like Kubernetes (openSUSE Kubic!), podman or transactional-updates.

 


Haben Sie Anmerkungen oder Nachfragen? Melden Sie sich unter blog%b1-systems.de
Col 2