Changing the colour of the root prompt in a bash shell
February 25, 2008 2 Comments
I’m terrible for forgetting to exit a root session after I’ve been performing administrative functions on my machine, so I looked for some way of reminding me, and found this simple solution:
Edit the /etc/bashrc file to include the following function….
function setprompt
{
local RED="[$(tput setaf 1)]"
local RESET="[$(tput sgr0)]"
if [ `id -u` = 0 ] # check if user is root
then
PS1="$RED[u@h:W]$RESET "
else
PS1="[u@h:W]$RESET "
fi
}
setprompt
This then changes the prompt colour to red (or any colour you like) when logged on as root…..

Interesting stuff…. looks like what I’ve been looking for, almost. When I login as root I get the red but the prompt is the string literal rather than evaluated as root@machine# or something like that.
Suspect an issue with type of quotes.
Thanks for giving me an idea where to start from
Tweaked this now…
function setprompt
{
local RED=”$(tput setaf 1)”
local RESET=”$(tput sgr0)”
if [ `id -u` = 0 ] # check if user is root
then
PS1=”$RED root@$HOSTNAME:# $RESET ”
else
PS1=”$USERNAME@$HOSTNAME:$ $RESET ”
fi
}
setprompt