Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - pre-commit hook error color

My pre-commit hook compresses/compiles css/js files. When an error occurs, I simply use echo to output the error and then exit 1. However, the text that's written to the console is WHITE so it's not easy to see when an error occurs.

Is there another way to write to the console (errOut?) that will make the text RED?

like image 905
Redtopia Avatar asked Sep 10 '25 22:09

Redtopia


2 Answers

Best way to deal with this is to colorize your hook output instead of the PS1 prompt, like so:

red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
no_color='\033[0m'

echo -e "\n${yellow}Executing pre-commit hook${no_color}\n"

... do your hook stuff ...

if [[ something bad happens ]]; then
    >&2 echo -e "\n${red}ERROR - Something BAD happened!\n${no_color}"
    exit 1
fi

echo -e "${green}Git hook was SUCCESSFUL!${no_color}\n"

Note: Using -e with echo is required - it specifies to interpret special characters, like colors and new lines. (http://ss64.com/bash/echo.html)

like image 193
Redtopia Avatar answered Sep 12 '25 13:09

Redtopia


It might be a good idea to customize you bash, like this:

0 ;) $ cat ~/.bashrc
PS1="\[\033[01;37m\]\$? \$(if [[ \$? == 0 ]]; then echo \"\[\033[01;32m\];)\"; else echo \"\[\033[01;31m\];(\"; fi) $(if [[ ${EUID} == 0 ]]; then echo
 '\[\033[01;31m\]\h'; else echo '\[\033[01;32m\]\u@\h'; fi)\[\033[01;34m\] \w \$\[\033[00m\] "

It displays a green happy face ;) if the last command finished with no errors, and a red sad face ;( if it failed, for example:

0 ;) $ cat 1.sh
#!/bin/bash
exit 1
0 ;) $ ./1.sh
1 ;( $ 
0 ;( $ cat 1.sh
#!/bin/bash
exit 0
0 ;) $ ./1.sh
0 ;) $

You can customize the output however you want.

The example was taken from here

In action: enter image description here

Update

For Git 2.5 for windows it should be

if ! \$?; then
  PS1="\[\e[1;32m\]Nice Work!\n\[\e[0;32m\]\u@\h \[\e[0;33m\]\w\[\e[0;37m\]\n\$ " 
else
  PS1="\[\e[1;31m\]Something is wrong!\n\[\e[0;32m\]\u@\h \[\e[0;33m\]\w\[\e[0;37m\]\n\$ "
fi 
like image 25
neshkeev Avatar answered Sep 12 '25 13:09

neshkeev