Search code examples
colorsprintfgit-bash

git bash - Use git colors in printf output


I've written a variant of git status. How do I use the green and red that git status uses for staged and unstaged changes to color my output? Preferably by finding the runtime git definitions of red and green, but that's not so important: a hard-coded solution will do.


Solution

  • Git would probably use ANSI escape code: https://en.wikipedia.org/wiki/ANSI_escape_code

    This typically means that you use -e in echo or %b in printf (tested with Git for Windows 2.43.0):

    declare color_red="\\e[1;31m"
    declare color_none="\\e[0m"
    declare color_green="\\e[1;32m"
    echo -e "${color_red}RED${color_none}"
    printf "%bRED%b" "${color_red}" "${color_none}"
    

    Default git color are handled by the color.status.<slot> and boolean color.status: I did not find default values using git config command but you can find a the code that's responsible for the default palette here.

    Edit: the colours above are colours that I use in my own projects. You can use Wikipedia as reference.

    git-prompt.sh use another variation of these colours: the difference with my colours are simply that I activated the Bold or increased intensity.

    If your shell supports it (Windows Terminal does, most Terminals on Linux should), you can also try 24 bits colours:

    echo -e '\e[38;2;255;0;0mRED\e[0m\e[38;2;0;255;0mGreen\e[0m'
    

    If you need other escape sequence, then this site can help you but it does not supports 24 bits colours.

    Last but not least, here is a screenshot of what this does with Windows Terminal

    enter image description here