2

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.

  • Which file are you editing/adding? – Wilf Sep 8 '15 at 21:30
  • This is a .bashrc include I am editing. I named the file .bash_prompt and I include it within my .bashrc. The sole purpose of this file is to load my alternative colors and allow me to edit PS1 outside of my bashrc. – ILikeTurtles Sep 8 '15 at 21:37
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.