Bash Prompt Color Scheme – How to Change Based on User

bashbashrccolors

My current prompt is colorized and edited as so –

#!/bin/bash

# GIT Prompt help
if tput setaf 1 &> /dev/null; then
    tput sgr0; # reset colors
    bold=$(tput bold);
    reset=$(tput sgr0);
    txtund=$(tput sgr 0 1);
    black=$(tput setaf 0);
    blue=$(tput setaf 33);
    cyan=$(tput setaf 37);
    green=$(tput setaf 64);
    orange=$(tput setaf 166);
    purple=$(tput setaf 125);
    red=$(tput setaf 124);
    violet=$(tput setaf 61);
    white=$(tput setaf 15);
    yellow=$(tput setaf 136);
else
    bold='';
    reset="\e[0m";
    black="\e[1;30m";
    blue="\e[1;34m";
    cyan="\e[1;36m";
    green="\e[1;32m";
    orange="\e[1;33m";
    purple="\e[1;35m";
    red="\e[1;31m";
    violet="\e[1;35m";
    white="\e[1;37m";
    yellow="\e[1;33m";
fi;
ORIG=$PS1
HOST=$HOSTNAME
PS1="\[${txtund}${green}\]${HOST}\[\[${reset}\]";
PS1+="\$(prompt_git \"\[${white}\] on \[${violet}\]\")";
PS1+="\[${reset}\]";
PS1+="\[ at - ${orange}\W\]";
PS1+="\[${reset}\]";
PS1+="\[ - \u \]";
PS1+="\n\$ ";

I know that the line PS1+="[ – \u ]"; will show me my current user. However, I want that section to be red if it is root. All other users should be the default color of gray. Is there a way to change the color in that section based off of current user or should I just declare a variable and use an IF statement to insert that section or a modified section with red as a color?

My expected output is gray named user for all normal users. Root should be red. This is BASH.

Best Answer

There are various ways you can check whether the user is root (to then set the PS1):

  • the user's name, using $USER, $(whoami) (the output of $(whoami). N.B. the superuser can be called something else, but usually is called root.
  • the user's ID, using $EUID or $UID (see here for some info). UID 0 is always the superuser.

So for instance you could replace the line PS1+="\[ - \u \]" with:

if [ $EUID -eq 0 ]; then
    PS1+="\[ - ${red}\u \]";
else
    PS1+="\[ - \u \]";
fi

You could also set another custom variable into the line:

PS1+="\[ - \u  ${usercolor}\]"

And use a conditional statement before if like this to change the colour:

if [ $EUID -eq 0 ]; then
    usercolor="\e[1;31m";
fi
Related Question