Mohan pd.
Mohan pd. Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

Colorize your linux Prompt and add GIT branch on it

Oct 19, 2019 · 1 min
Colorize your linux Prompt and add GIT branch on it

Majority of linux distributions contains a /etc/profile.d which contain a few bash script that are executed on bash login you could add the following file there, the name is not important just need to end in .sh e.g. /etc/profile.d/PS1-git.sh In order to add the file to /etc/profile.d you probably would need root access.

# Define here your own colors.
# @see https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
USER_COLOR='32'
ROOT_COLOR='31'
GITCOLOR='33'

RESET_COLORS='\[\e[0m\]'

[ $(whoami) = 'root' ] && DCOLOR=$ROOT_COLOR || DCOLOR=$USER_COLOR

parse_git_branch() {
	BRANCH=`git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`

	if [ ! -z "$BRANCH" ]; then
		echo " ($BRANCH) "
	else
		echo ""
	fi
}

# Enable/disable or add new parts for customize your prompt
PS1=''
PS1+='\[\e[1;${DCOLOR}m\]'   # base color
PS1+='['                     # start first group
#	PS1+='\u'                # current user
	PS1+='\[email protected]\h'             # current user at host
	PS1+=' '                 # separator
	PS1+='\w'                # current directory (full path)
#	PS1+='\W'                # current directory (basename)
PS1+=']'                     # end first group
PS1+=$RESET_COLORS           # RESET_COLORS COLORS
PS1+='\[\e[1;${GITCOLOR}m\]' # GIT COLOR
PS1+='$(parse_git_branch)'   # git Branch
PS1+=$RESET_COLORS           # RESET_COLORS COLORS
PS1+='\[\e[1;${DCOLOR}m\]'   # base color
PS1+='\$'                    # root or user
PS1+=' '                     # separator
PS1+=$RESET_COLORS           # RESET_COLORS COLORS

unset USER_COLOR
unset ROOT_COLOR

Once you add it, run bash, or open a new terminal, and if you haven’t done any change, you would see your prompt as green, If not, it might be because your distro haven’t configured the use of profile.d for that you can add this to the file ~/.bashrc

if [ -f /etc/profile.d/ ]
 // LOOP /etc/profile.d/*
fi