Force "git status" to output color on the terminal (inside a script) Force "git status" to output color on the terminal (inside a script) unix unix

Force "git status" to output color on the terminal (inside a script)


To avoid changing your git config, you can enable colour just for the current command by passing a config variable with -c.

For the status command, the variable is color.status:

    git -c color.status=always status | less -REX

For diff, show, log and grep commands, the variable is color.ui:

    git -c color.ui=always diff | less -REX

Note that -c must come before the status or diff argument, and not after.

Alternatively, for diff, show, log and grep commands, you can use --color=always after the command:

    git diff --color=always | less -REX

Note: As Steven said, if you are trying to extract meaningful data, then instead of parsing colours to extract meaning, you can use --porcelain to get more parser-friendly output.

    git status --porcelain | awk ...

Then if you wanted, you could reintroduce colours later.

To get the user's configured colours, you can use git config --get-colour:

    reset_color="$(tput sgr0)"    remote_branch_color="$(git config --get-color color.branch.remote white)"    echo "Pushing to ${remote_branch_color}${branch_name}${reset_color}"

Some more examples here.


EDIT:

I would like to make a strong recommendation that parsing colors is a generally ill-conceived idea.

Part of why i wanted it was so I can both parse it and pass it along in my own script output. This is... okay, but it would probably be saner to use porcelain or some such and re-build the colored parts myself!

Original answer follows.


I keep finding answers really quickly after asking questions. Something to do with thinking about a problem long enough to write it out that you formulate better approaches for solving it. Anyway, the solution to this is just

git config color.status always

I imagine that a general purpose solution involves expect or something pty related to force any programs that require it into thinking they are on a terminal.


I had this same issue when using a git alias that executes a shell command. Apparently the git shell doesn't inherit from the current environment, so it knows nothing about my coloring settings.

In addition to adding the global git color ui setting, I fixed this by making my alias look like below, its the secondary command that requires being told to use colors, as git will by default as of whatever 1.8.x version people have mentioned.

[alias]  ignored = !git ls-files -v|grep --color '^h'

This produces equivalent colorized output now when run as the alias the same as if I just ran the command.

For sed, this other answer appears to work more reliably, use tput.https://unix.stackexchange.com/a/45954