简体   繁体   中英

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 ?

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 )

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: 在此处输入图片说明

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM