Search code examples
windowsbashgitterminalwindows-terminal

How to use function on git-prompt on Git Bash for Windows?


I want to use the last exit code to customize my bash prompt. So following this question I should add $? inside a function:

PROMPT_COMMAND=__prompt_command

__prompt_command() {
    local EXIT="$?"
    ...

I tried many times, but whenever I add a function on my C:\Program Files\Git\etc\profile.d\git-prompt.sh file, Git Bash can't run this file, and it doesn't use it.

Is there a way to use a function on git-prompt.sh on Git Bash for Windows, or another approach to use the last exit code to customize the bash prompt?


Solution

  • Follow these instructions to configure your git-bash prompt.

    First, open git-bash, and cd to your ~ directory.

    Using vim or nano, edit your ~/.bash_profile file to contain the following two lines:

    test -f ~/.profile && . ~/.profile
    test -f ~/.bashrc && . ~/.bashrc
    

    Then create a ~/.bashrc file and add your custom prompt command function in this file:

    PROMPT_COMMAND=__prompt_command
    
    __prompt_command() {
        local EXIT="$?"
        # The rest of your code here
    }
    

    Make sure your changes saved correctly for both your ~/.bash_profile and ~/.bashrc files.

    Open a new git-bash window. Assuming you have no bugs in your __prompt_command() function, your custom prompt should display properly.

    If you quickly want to test your prompt, you can instead just run source ~/.bashrc in your current git-bash window rather than launching a second one.