Changing the colour of the root prompt in a bash shell

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…..

Red Shell Prompt


2 Responses to Changing the colour of the root prompt in a bash shell

  1. DaFoot says:

    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 :)

  2. Paul Roach says:

    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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>